repository_name
stringclasses
316 values
func_path_in_repository
stringlengths
6
223
func_name
stringlengths
1
134
language
stringclasses
1 value
func_code_string
stringlengths
57
65.5k
func_documentation_string
stringlengths
1
46.3k
split_name
stringclasses
1 value
func_code_url
stringlengths
91
315
called_functions
listlengths
1
156
enclosing_scope
stringlengths
2
1.48M
saltstack/salt
salt/modules/jenkinsmod.py
job_status
python
def job_status(name=None): ''' Return the current status, enabled or disabled, of the job. :param name: The name of the job to return status for :return: Return true if enabled or false if disabled. CLI Example: .. code-block:: bash salt '*' jenkins.job_status jobname ''' if not name: raise SaltInvocationError('Required parameter \'name\' is missing') server = _connect() if not job_exists(name): raise CommandExecutionError('Job \'{0}\' does not exist'.format(name)) return server.get_job_info('empty')['buildable']
Return the current status, enabled or disabled, of the job. :param name: The name of the job to return status for :return: Return true if enabled or false if disabled. CLI Example: .. code-block:: bash salt '*' jenkins.job_status jobname
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/jenkinsmod.py#L433-L456
[ "def _connect():\n '''\n Return server object used to interact with Jenkins.\n\n :return: server object used to interact with Jenkins\n '''\n jenkins_url = __salt__['config.get']('jenkins.url') or \\\n __salt__['config.get']('jenkins:url') or \\\n __salt__['pillar.get']('jenkins.url')\n\n jenkins_user = __salt__['config.get']('jenkins.user') or \\\n __salt__['config.get']('jenkins:user') or \\\n __salt__['pillar.get']('jenkins.user')\n\n jenkins_password = __salt__['config.get']('jenkins.password') or \\\n __salt__['config.get']('jenkins:password') or \\\n __salt__['pillar.get']('jenkins.password')\n\n if not jenkins_url:\n raise SaltInvocationError('No Jenkins URL found.')\n\n return jenkins.Jenkins(jenkins_url,\n username=jenkins_user,\n password=jenkins_password)\n", "def job_exists(name=None):\n '''\n Check whether the job exists in configured Jenkins jobs.\n\n :param name: The name of the job is check if it exists.\n :return: True if job exists, False if job does not exist.\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' jenkins.job_exists jobname\n\n '''\n if not name:\n raise SaltInvocationError('Required parameter \\'name\\' is missing')\n\n server = _connect()\n if server.job_exists(name):\n return True\n else:\n return False\n" ]
# -*- coding: utf-8 -*- ''' Module for controlling Jenkins :depends: python-jenkins .. versionadded:: 2016.3.0 :depends: python-jenkins_ Python module (not to be confused with jenkins_) .. _python-jenkins: https://pypi.python.org/pypi/python-jenkins .. _jenkins: https://pypi.python.org/pypi/jenkins :configuration: This module can be used by either passing an api key and version directly or by specifying both in a configuration profile in the salt master/minion config. For example: .. code-block:: yaml jenkins: api_key: peWcBiMOS9HrZG15peWcBiMOS9HrZG15 ''' # Import Python libs from __future__ import absolute_import, print_function, unicode_literals import logging # Import Salt libs import salt.utils.stringutils try: import jenkins HAS_JENKINS = True except ImportError: HAS_JENKINS = False import salt.utils.files # Import 3rd-party libs # pylint: disable=import-error,no-name-in-module,redefined-builtin from salt.exceptions import CommandExecutionError, SaltInvocationError # pylint: enable=import-error,no-name-in-module log = logging.getLogger(__name__) __virtualname__ = 'jenkins' def __virtual__(): ''' Return virtual name of the module. :return: The virtual name of the module. ''' if HAS_JENKINS: if hasattr(jenkins, 'Jenkins'): return __virtualname__ else: return (False, 'The wrong Python module appears to be installed. Please ' 'make sure that \'python-jenkins\' is installed, not ' '\'jenkins\'.') return (False, 'The jenkins execution module cannot be loaded: ' 'python-jenkins is not installed.') def _connect(): ''' Return server object used to interact with Jenkins. :return: server object used to interact with Jenkins ''' jenkins_url = __salt__['config.get']('jenkins.url') or \ __salt__['config.get']('jenkins:url') or \ __salt__['pillar.get']('jenkins.url') jenkins_user = __salt__['config.get']('jenkins.user') or \ __salt__['config.get']('jenkins:user') or \ __salt__['pillar.get']('jenkins.user') jenkins_password = __salt__['config.get']('jenkins.password') or \ __salt__['config.get']('jenkins:password') or \ __salt__['pillar.get']('jenkins.password') if not jenkins_url: raise SaltInvocationError('No Jenkins URL found.') return jenkins.Jenkins(jenkins_url, username=jenkins_user, password=jenkins_password) def _retrieve_config_xml(config_xml, saltenv): ''' Helper to cache the config XML and raise a CommandExecutionError if we fail to do so. If we successfully cache the file, return the cached path. ''' ret = __salt__['cp.cache_file'](config_xml, saltenv) if not ret: raise CommandExecutionError('Failed to retrieve {0}'.format(config_xml)) return ret def run(script): ''' .. versionadded:: 2017.7.0 Execute a script on the jenkins master :param script: The script CLI Example: .. code-block:: bash salt '*' jenkins.run 'Jenkins.instance.doSafeRestart()' ''' server = _connect() return server.run_script(script) def get_version(): ''' Return version of Jenkins :return: The version of Jenkins CLI Example: .. code-block:: bash salt '*' jenkins.get_version ''' server = _connect() version = server.get_version() if version: return version return False def get_jobs(): ''' Return the currently configured jobs. :return: The currently configured jobs. CLI Example: .. code-block:: bash salt '*' jenkins.get_jobs ''' server = _connect() jobs = server.get_jobs() if jobs: return jobs return {} def job_exists(name=None): ''' Check whether the job exists in configured Jenkins jobs. :param name: The name of the job is check if it exists. :return: True if job exists, False if job does not exist. CLI Example: .. code-block:: bash salt '*' jenkins.job_exists jobname ''' if not name: raise SaltInvocationError('Required parameter \'name\' is missing') server = _connect() if server.job_exists(name): return True else: return False def get_job_info(name=None): ''' Return information about the Jenkins job. :param name: The name of the job is check if it exists. :return: Information about the Jenkins job. CLI Example: .. code-block:: bash salt '*' jenkins.get_job_info jobname ''' if not name: raise SaltInvocationError('Required parameter \'name\' is missing') server = _connect() if not job_exists(name): raise CommandExecutionError('Job \'{0}\' does not exist'.format(name)) job_info = server.get_job_info(name) if job_info: return job_info return False def build_job(name=None, parameters=None): ''' Initiate a build for the provided job. :param name: The name of the job is check if it exists. :param parameters: Parameters to send to the job. :return: True is successful, otherwise raise an exception. CLI Example: .. code-block:: bash salt '*' jenkins.build_job jobname ''' if not name: raise SaltInvocationError('Required parameter \'name\' is missing') server = _connect() if not job_exists(name): raise CommandExecutionError('Job \'{0}\' does not exist.'.format(name)) try: server.build_job(name, parameters) except jenkins.JenkinsException as err: raise CommandExecutionError( 'Encountered error building job \'{0}\': {1}'.format(name, err) ) return True def create_job(name=None, config_xml=None, saltenv='base'): ''' Return the configuration file. :param name: The name of the job is check if it exists. :param config_xml: The configuration file to use to create the job. :param saltenv: The environment to look for the file in. :return: The configuration file used for the job. CLI Example: .. code-block:: bash salt '*' jenkins.create_job jobname salt '*' jenkins.create_job jobname config_xml='salt://jenkins/config.xml' ''' if not name: raise SaltInvocationError('Required parameter \'name\' is missing') if job_exists(name): raise CommandExecutionError('Job \'{0}\' already exists'.format(name)) if not config_xml: config_xml = jenkins.EMPTY_CONFIG_XML else: config_xml_file = _retrieve_config_xml(config_xml, saltenv) with salt.utils.files.fopen(config_xml_file) as _fp: config_xml = salt.utils.stringutils.to_unicode(_fp.read()) server = _connect() try: server.create_job(name, config_xml) except jenkins.JenkinsException as err: raise CommandExecutionError( 'Encountered error creating job \'{0}\': {1}'.format(name, err) ) return config_xml def update_job(name=None, config_xml=None, saltenv='base'): ''' Return the updated configuration file. :param name: The name of the job is check if it exists. :param config_xml: The configuration file to use to create the job. :param saltenv: The environment to look for the file in. :return: The configuration file used for the job. CLI Example: .. code-block:: bash salt '*' jenkins.update_job jobname salt '*' jenkins.update_job jobname config_xml='salt://jenkins/config.xml' ''' if not name: raise SaltInvocationError('Required parameter \'name\' is missing') if not config_xml: config_xml = jenkins.EMPTY_CONFIG_XML else: config_xml_file = _retrieve_config_xml(config_xml, saltenv) with salt.utils.files.fopen(config_xml_file) as _fp: config_xml = salt.utils.stringutils.to_unicode(_fp.read()) server = _connect() try: server.reconfig_job(name, config_xml) except jenkins.JenkinsException as err: raise CommandExecutionError( 'Encountered error updating job \'{0}\': {1}'.format(name, err) ) return config_xml def delete_job(name=None): ''' Return true is job is deleted successfully. :param name: The name of the job to delete. :return: Return true if job is deleted successfully. CLI Example: .. code-block:: bash salt '*' jenkins.delete_job jobname ''' if not name: raise SaltInvocationError('Required parameter \'name\' is missing') server = _connect() if not job_exists(name): raise CommandExecutionError('Job \'{0}\' does not exist'.format(name)) try: server.delete_job(name) except jenkins.JenkinsException as err: raise CommandExecutionError( 'Encountered error deleting job \'{0}\': {1}'.format(name, err) ) return True def enable_job(name=None): ''' Return true is job is enabled successfully. :param name: The name of the job to enable. :return: Return true if job is enabled successfully. CLI Example: .. code-block:: bash salt '*' jenkins.enable_job jobname ''' if not name: raise SaltInvocationError('Required parameter \'name\' is missing') server = _connect() if not job_exists(name): raise CommandExecutionError('Job \'{0}\' does not exist'.format(name)) try: server.enable_job(name) except jenkins.JenkinsException as err: raise CommandExecutionError( 'Encountered error enabling job \'{0}\': {1}'.format(name, err) ) return True def disable_job(name=None): ''' Return true is job is disabled successfully. :param name: The name of the job to disable. :return: Return true if job is disabled successfully. CLI Example: .. code-block:: bash salt '*' jenkins.disable_job jobname ''' if not name: raise SaltInvocationError('Required parameter \'name\' is missing') server = _connect() if not job_exists(name): raise CommandExecutionError('Job \'{0}\' does not exist'.format(name)) try: server.disable_job(name) except jenkins.JenkinsException as err: raise CommandExecutionError( 'Encountered error disabling job \'{0}\': {1}'.format(name, err) ) return True def get_job_config(name=None): ''' Return the current job configuration for the provided job. :param name: The name of the job to return the configuration for. :return: The configuration for the job specified. CLI Example: .. code-block:: bash salt '*' jenkins.get_job_config jobname ''' if not name: raise SaltInvocationError('Required parameter \'name\' is missing') server = _connect() if not job_exists(name): raise CommandExecutionError('Job \'{0}\' does not exist'.format(name)) job_info = server.get_job_config(name) return job_info def plugin_installed(name): ''' .. versionadded:: 2016.11.0 Return if the plugin is installed for the provided plugin name. :param name: The name of the parameter to confirm installation. :return: True if plugin exists, False if plugin does not exist. CLI Example: .. code-block:: bash salt '*' jenkins.plugin_installed pluginName ''' server = _connect() plugins = server.get_plugins() exists = [plugin for plugin in plugins.keys() if name in plugin] if exists: return True else: return False
saltstack/salt
salt/modules/jenkinsmod.py
get_job_config
python
def get_job_config(name=None): ''' Return the current job configuration for the provided job. :param name: The name of the job to return the configuration for. :return: The configuration for the job specified. CLI Example: .. code-block:: bash salt '*' jenkins.get_job_config jobname ''' if not name: raise SaltInvocationError('Required parameter \'name\' is missing') server = _connect() if not job_exists(name): raise CommandExecutionError('Job \'{0}\' does not exist'.format(name)) job_info = server.get_job_config(name) return job_info
Return the current job configuration for the provided job. :param name: The name of the job to return the configuration for. :return: The configuration for the job specified. CLI Example: .. code-block:: bash salt '*' jenkins.get_job_config jobname
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/jenkinsmod.py#L459-L483
[ "def _connect():\n '''\n Return server object used to interact with Jenkins.\n\n :return: server object used to interact with Jenkins\n '''\n jenkins_url = __salt__['config.get']('jenkins.url') or \\\n __salt__['config.get']('jenkins:url') or \\\n __salt__['pillar.get']('jenkins.url')\n\n jenkins_user = __salt__['config.get']('jenkins.user') or \\\n __salt__['config.get']('jenkins:user') or \\\n __salt__['pillar.get']('jenkins.user')\n\n jenkins_password = __salt__['config.get']('jenkins.password') or \\\n __salt__['config.get']('jenkins:password') or \\\n __salt__['pillar.get']('jenkins.password')\n\n if not jenkins_url:\n raise SaltInvocationError('No Jenkins URL found.')\n\n return jenkins.Jenkins(jenkins_url,\n username=jenkins_user,\n password=jenkins_password)\n", "def job_exists(name=None):\n '''\n Check whether the job exists in configured Jenkins jobs.\n\n :param name: The name of the job is check if it exists.\n :return: True if job exists, False if job does not exist.\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' jenkins.job_exists jobname\n\n '''\n if not name:\n raise SaltInvocationError('Required parameter \\'name\\' is missing')\n\n server = _connect()\n if server.job_exists(name):\n return True\n else:\n return False\n" ]
# -*- coding: utf-8 -*- ''' Module for controlling Jenkins :depends: python-jenkins .. versionadded:: 2016.3.0 :depends: python-jenkins_ Python module (not to be confused with jenkins_) .. _python-jenkins: https://pypi.python.org/pypi/python-jenkins .. _jenkins: https://pypi.python.org/pypi/jenkins :configuration: This module can be used by either passing an api key and version directly or by specifying both in a configuration profile in the salt master/minion config. For example: .. code-block:: yaml jenkins: api_key: peWcBiMOS9HrZG15peWcBiMOS9HrZG15 ''' # Import Python libs from __future__ import absolute_import, print_function, unicode_literals import logging # Import Salt libs import salt.utils.stringutils try: import jenkins HAS_JENKINS = True except ImportError: HAS_JENKINS = False import salt.utils.files # Import 3rd-party libs # pylint: disable=import-error,no-name-in-module,redefined-builtin from salt.exceptions import CommandExecutionError, SaltInvocationError # pylint: enable=import-error,no-name-in-module log = logging.getLogger(__name__) __virtualname__ = 'jenkins' def __virtual__(): ''' Return virtual name of the module. :return: The virtual name of the module. ''' if HAS_JENKINS: if hasattr(jenkins, 'Jenkins'): return __virtualname__ else: return (False, 'The wrong Python module appears to be installed. Please ' 'make sure that \'python-jenkins\' is installed, not ' '\'jenkins\'.') return (False, 'The jenkins execution module cannot be loaded: ' 'python-jenkins is not installed.') def _connect(): ''' Return server object used to interact with Jenkins. :return: server object used to interact with Jenkins ''' jenkins_url = __salt__['config.get']('jenkins.url') or \ __salt__['config.get']('jenkins:url') or \ __salt__['pillar.get']('jenkins.url') jenkins_user = __salt__['config.get']('jenkins.user') or \ __salt__['config.get']('jenkins:user') or \ __salt__['pillar.get']('jenkins.user') jenkins_password = __salt__['config.get']('jenkins.password') or \ __salt__['config.get']('jenkins:password') or \ __salt__['pillar.get']('jenkins.password') if not jenkins_url: raise SaltInvocationError('No Jenkins URL found.') return jenkins.Jenkins(jenkins_url, username=jenkins_user, password=jenkins_password) def _retrieve_config_xml(config_xml, saltenv): ''' Helper to cache the config XML and raise a CommandExecutionError if we fail to do so. If we successfully cache the file, return the cached path. ''' ret = __salt__['cp.cache_file'](config_xml, saltenv) if not ret: raise CommandExecutionError('Failed to retrieve {0}'.format(config_xml)) return ret def run(script): ''' .. versionadded:: 2017.7.0 Execute a script on the jenkins master :param script: The script CLI Example: .. code-block:: bash salt '*' jenkins.run 'Jenkins.instance.doSafeRestart()' ''' server = _connect() return server.run_script(script) def get_version(): ''' Return version of Jenkins :return: The version of Jenkins CLI Example: .. code-block:: bash salt '*' jenkins.get_version ''' server = _connect() version = server.get_version() if version: return version return False def get_jobs(): ''' Return the currently configured jobs. :return: The currently configured jobs. CLI Example: .. code-block:: bash salt '*' jenkins.get_jobs ''' server = _connect() jobs = server.get_jobs() if jobs: return jobs return {} def job_exists(name=None): ''' Check whether the job exists in configured Jenkins jobs. :param name: The name of the job is check if it exists. :return: True if job exists, False if job does not exist. CLI Example: .. code-block:: bash salt '*' jenkins.job_exists jobname ''' if not name: raise SaltInvocationError('Required parameter \'name\' is missing') server = _connect() if server.job_exists(name): return True else: return False def get_job_info(name=None): ''' Return information about the Jenkins job. :param name: The name of the job is check if it exists. :return: Information about the Jenkins job. CLI Example: .. code-block:: bash salt '*' jenkins.get_job_info jobname ''' if not name: raise SaltInvocationError('Required parameter \'name\' is missing') server = _connect() if not job_exists(name): raise CommandExecutionError('Job \'{0}\' does not exist'.format(name)) job_info = server.get_job_info(name) if job_info: return job_info return False def build_job(name=None, parameters=None): ''' Initiate a build for the provided job. :param name: The name of the job is check if it exists. :param parameters: Parameters to send to the job. :return: True is successful, otherwise raise an exception. CLI Example: .. code-block:: bash salt '*' jenkins.build_job jobname ''' if not name: raise SaltInvocationError('Required parameter \'name\' is missing') server = _connect() if not job_exists(name): raise CommandExecutionError('Job \'{0}\' does not exist.'.format(name)) try: server.build_job(name, parameters) except jenkins.JenkinsException as err: raise CommandExecutionError( 'Encountered error building job \'{0}\': {1}'.format(name, err) ) return True def create_job(name=None, config_xml=None, saltenv='base'): ''' Return the configuration file. :param name: The name of the job is check if it exists. :param config_xml: The configuration file to use to create the job. :param saltenv: The environment to look for the file in. :return: The configuration file used for the job. CLI Example: .. code-block:: bash salt '*' jenkins.create_job jobname salt '*' jenkins.create_job jobname config_xml='salt://jenkins/config.xml' ''' if not name: raise SaltInvocationError('Required parameter \'name\' is missing') if job_exists(name): raise CommandExecutionError('Job \'{0}\' already exists'.format(name)) if not config_xml: config_xml = jenkins.EMPTY_CONFIG_XML else: config_xml_file = _retrieve_config_xml(config_xml, saltenv) with salt.utils.files.fopen(config_xml_file) as _fp: config_xml = salt.utils.stringutils.to_unicode(_fp.read()) server = _connect() try: server.create_job(name, config_xml) except jenkins.JenkinsException as err: raise CommandExecutionError( 'Encountered error creating job \'{0}\': {1}'.format(name, err) ) return config_xml def update_job(name=None, config_xml=None, saltenv='base'): ''' Return the updated configuration file. :param name: The name of the job is check if it exists. :param config_xml: The configuration file to use to create the job. :param saltenv: The environment to look for the file in. :return: The configuration file used for the job. CLI Example: .. code-block:: bash salt '*' jenkins.update_job jobname salt '*' jenkins.update_job jobname config_xml='salt://jenkins/config.xml' ''' if not name: raise SaltInvocationError('Required parameter \'name\' is missing') if not config_xml: config_xml = jenkins.EMPTY_CONFIG_XML else: config_xml_file = _retrieve_config_xml(config_xml, saltenv) with salt.utils.files.fopen(config_xml_file) as _fp: config_xml = salt.utils.stringutils.to_unicode(_fp.read()) server = _connect() try: server.reconfig_job(name, config_xml) except jenkins.JenkinsException as err: raise CommandExecutionError( 'Encountered error updating job \'{0}\': {1}'.format(name, err) ) return config_xml def delete_job(name=None): ''' Return true is job is deleted successfully. :param name: The name of the job to delete. :return: Return true if job is deleted successfully. CLI Example: .. code-block:: bash salt '*' jenkins.delete_job jobname ''' if not name: raise SaltInvocationError('Required parameter \'name\' is missing') server = _connect() if not job_exists(name): raise CommandExecutionError('Job \'{0}\' does not exist'.format(name)) try: server.delete_job(name) except jenkins.JenkinsException as err: raise CommandExecutionError( 'Encountered error deleting job \'{0}\': {1}'.format(name, err) ) return True def enable_job(name=None): ''' Return true is job is enabled successfully. :param name: The name of the job to enable. :return: Return true if job is enabled successfully. CLI Example: .. code-block:: bash salt '*' jenkins.enable_job jobname ''' if not name: raise SaltInvocationError('Required parameter \'name\' is missing') server = _connect() if not job_exists(name): raise CommandExecutionError('Job \'{0}\' does not exist'.format(name)) try: server.enable_job(name) except jenkins.JenkinsException as err: raise CommandExecutionError( 'Encountered error enabling job \'{0}\': {1}'.format(name, err) ) return True def disable_job(name=None): ''' Return true is job is disabled successfully. :param name: The name of the job to disable. :return: Return true if job is disabled successfully. CLI Example: .. code-block:: bash salt '*' jenkins.disable_job jobname ''' if not name: raise SaltInvocationError('Required parameter \'name\' is missing') server = _connect() if not job_exists(name): raise CommandExecutionError('Job \'{0}\' does not exist'.format(name)) try: server.disable_job(name) except jenkins.JenkinsException as err: raise CommandExecutionError( 'Encountered error disabling job \'{0}\': {1}'.format(name, err) ) return True def job_status(name=None): ''' Return the current status, enabled or disabled, of the job. :param name: The name of the job to return status for :return: Return true if enabled or false if disabled. CLI Example: .. code-block:: bash salt '*' jenkins.job_status jobname ''' if not name: raise SaltInvocationError('Required parameter \'name\' is missing') server = _connect() if not job_exists(name): raise CommandExecutionError('Job \'{0}\' does not exist'.format(name)) return server.get_job_info('empty')['buildable'] def plugin_installed(name): ''' .. versionadded:: 2016.11.0 Return if the plugin is installed for the provided plugin name. :param name: The name of the parameter to confirm installation. :return: True if plugin exists, False if plugin does not exist. CLI Example: .. code-block:: bash salt '*' jenkins.plugin_installed pluginName ''' server = _connect() plugins = server.get_plugins() exists = [plugin for plugin in plugins.keys() if name in plugin] if exists: return True else: return False
saltstack/salt
salt/modules/jenkinsmod.py
plugin_installed
python
def plugin_installed(name): ''' .. versionadded:: 2016.11.0 Return if the plugin is installed for the provided plugin name. :param name: The name of the parameter to confirm installation. :return: True if plugin exists, False if plugin does not exist. CLI Example: .. code-block:: bash salt '*' jenkins.plugin_installed pluginName ''' server = _connect() plugins = server.get_plugins() exists = [plugin for plugin in plugins.keys() if name in plugin] if exists: return True else: return False
.. versionadded:: 2016.11.0 Return if the plugin is installed for the provided plugin name. :param name: The name of the parameter to confirm installation. :return: True if plugin exists, False if plugin does not exist. CLI Example: .. code-block:: bash salt '*' jenkins.plugin_installed pluginName
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/jenkinsmod.py#L486-L511
[ "def _connect():\n '''\n Return server object used to interact with Jenkins.\n\n :return: server object used to interact with Jenkins\n '''\n jenkins_url = __salt__['config.get']('jenkins.url') or \\\n __salt__['config.get']('jenkins:url') or \\\n __salt__['pillar.get']('jenkins.url')\n\n jenkins_user = __salt__['config.get']('jenkins.user') or \\\n __salt__['config.get']('jenkins:user') or \\\n __salt__['pillar.get']('jenkins.user')\n\n jenkins_password = __salt__['config.get']('jenkins.password') or \\\n __salt__['config.get']('jenkins:password') or \\\n __salt__['pillar.get']('jenkins.password')\n\n if not jenkins_url:\n raise SaltInvocationError('No Jenkins URL found.')\n\n return jenkins.Jenkins(jenkins_url,\n username=jenkins_user,\n password=jenkins_password)\n" ]
# -*- coding: utf-8 -*- ''' Module for controlling Jenkins :depends: python-jenkins .. versionadded:: 2016.3.0 :depends: python-jenkins_ Python module (not to be confused with jenkins_) .. _python-jenkins: https://pypi.python.org/pypi/python-jenkins .. _jenkins: https://pypi.python.org/pypi/jenkins :configuration: This module can be used by either passing an api key and version directly or by specifying both in a configuration profile in the salt master/minion config. For example: .. code-block:: yaml jenkins: api_key: peWcBiMOS9HrZG15peWcBiMOS9HrZG15 ''' # Import Python libs from __future__ import absolute_import, print_function, unicode_literals import logging # Import Salt libs import salt.utils.stringutils try: import jenkins HAS_JENKINS = True except ImportError: HAS_JENKINS = False import salt.utils.files # Import 3rd-party libs # pylint: disable=import-error,no-name-in-module,redefined-builtin from salt.exceptions import CommandExecutionError, SaltInvocationError # pylint: enable=import-error,no-name-in-module log = logging.getLogger(__name__) __virtualname__ = 'jenkins' def __virtual__(): ''' Return virtual name of the module. :return: The virtual name of the module. ''' if HAS_JENKINS: if hasattr(jenkins, 'Jenkins'): return __virtualname__ else: return (False, 'The wrong Python module appears to be installed. Please ' 'make sure that \'python-jenkins\' is installed, not ' '\'jenkins\'.') return (False, 'The jenkins execution module cannot be loaded: ' 'python-jenkins is not installed.') def _connect(): ''' Return server object used to interact with Jenkins. :return: server object used to interact with Jenkins ''' jenkins_url = __salt__['config.get']('jenkins.url') or \ __salt__['config.get']('jenkins:url') or \ __salt__['pillar.get']('jenkins.url') jenkins_user = __salt__['config.get']('jenkins.user') or \ __salt__['config.get']('jenkins:user') or \ __salt__['pillar.get']('jenkins.user') jenkins_password = __salt__['config.get']('jenkins.password') or \ __salt__['config.get']('jenkins:password') or \ __salt__['pillar.get']('jenkins.password') if not jenkins_url: raise SaltInvocationError('No Jenkins URL found.') return jenkins.Jenkins(jenkins_url, username=jenkins_user, password=jenkins_password) def _retrieve_config_xml(config_xml, saltenv): ''' Helper to cache the config XML and raise a CommandExecutionError if we fail to do so. If we successfully cache the file, return the cached path. ''' ret = __salt__['cp.cache_file'](config_xml, saltenv) if not ret: raise CommandExecutionError('Failed to retrieve {0}'.format(config_xml)) return ret def run(script): ''' .. versionadded:: 2017.7.0 Execute a script on the jenkins master :param script: The script CLI Example: .. code-block:: bash salt '*' jenkins.run 'Jenkins.instance.doSafeRestart()' ''' server = _connect() return server.run_script(script) def get_version(): ''' Return version of Jenkins :return: The version of Jenkins CLI Example: .. code-block:: bash salt '*' jenkins.get_version ''' server = _connect() version = server.get_version() if version: return version return False def get_jobs(): ''' Return the currently configured jobs. :return: The currently configured jobs. CLI Example: .. code-block:: bash salt '*' jenkins.get_jobs ''' server = _connect() jobs = server.get_jobs() if jobs: return jobs return {} def job_exists(name=None): ''' Check whether the job exists in configured Jenkins jobs. :param name: The name of the job is check if it exists. :return: True if job exists, False if job does not exist. CLI Example: .. code-block:: bash salt '*' jenkins.job_exists jobname ''' if not name: raise SaltInvocationError('Required parameter \'name\' is missing') server = _connect() if server.job_exists(name): return True else: return False def get_job_info(name=None): ''' Return information about the Jenkins job. :param name: The name of the job is check if it exists. :return: Information about the Jenkins job. CLI Example: .. code-block:: bash salt '*' jenkins.get_job_info jobname ''' if not name: raise SaltInvocationError('Required parameter \'name\' is missing') server = _connect() if not job_exists(name): raise CommandExecutionError('Job \'{0}\' does not exist'.format(name)) job_info = server.get_job_info(name) if job_info: return job_info return False def build_job(name=None, parameters=None): ''' Initiate a build for the provided job. :param name: The name of the job is check if it exists. :param parameters: Parameters to send to the job. :return: True is successful, otherwise raise an exception. CLI Example: .. code-block:: bash salt '*' jenkins.build_job jobname ''' if not name: raise SaltInvocationError('Required parameter \'name\' is missing') server = _connect() if not job_exists(name): raise CommandExecutionError('Job \'{0}\' does not exist.'.format(name)) try: server.build_job(name, parameters) except jenkins.JenkinsException as err: raise CommandExecutionError( 'Encountered error building job \'{0}\': {1}'.format(name, err) ) return True def create_job(name=None, config_xml=None, saltenv='base'): ''' Return the configuration file. :param name: The name of the job is check if it exists. :param config_xml: The configuration file to use to create the job. :param saltenv: The environment to look for the file in. :return: The configuration file used for the job. CLI Example: .. code-block:: bash salt '*' jenkins.create_job jobname salt '*' jenkins.create_job jobname config_xml='salt://jenkins/config.xml' ''' if not name: raise SaltInvocationError('Required parameter \'name\' is missing') if job_exists(name): raise CommandExecutionError('Job \'{0}\' already exists'.format(name)) if not config_xml: config_xml = jenkins.EMPTY_CONFIG_XML else: config_xml_file = _retrieve_config_xml(config_xml, saltenv) with salt.utils.files.fopen(config_xml_file) as _fp: config_xml = salt.utils.stringutils.to_unicode(_fp.read()) server = _connect() try: server.create_job(name, config_xml) except jenkins.JenkinsException as err: raise CommandExecutionError( 'Encountered error creating job \'{0}\': {1}'.format(name, err) ) return config_xml def update_job(name=None, config_xml=None, saltenv='base'): ''' Return the updated configuration file. :param name: The name of the job is check if it exists. :param config_xml: The configuration file to use to create the job. :param saltenv: The environment to look for the file in. :return: The configuration file used for the job. CLI Example: .. code-block:: bash salt '*' jenkins.update_job jobname salt '*' jenkins.update_job jobname config_xml='salt://jenkins/config.xml' ''' if not name: raise SaltInvocationError('Required parameter \'name\' is missing') if not config_xml: config_xml = jenkins.EMPTY_CONFIG_XML else: config_xml_file = _retrieve_config_xml(config_xml, saltenv) with salt.utils.files.fopen(config_xml_file) as _fp: config_xml = salt.utils.stringutils.to_unicode(_fp.read()) server = _connect() try: server.reconfig_job(name, config_xml) except jenkins.JenkinsException as err: raise CommandExecutionError( 'Encountered error updating job \'{0}\': {1}'.format(name, err) ) return config_xml def delete_job(name=None): ''' Return true is job is deleted successfully. :param name: The name of the job to delete. :return: Return true if job is deleted successfully. CLI Example: .. code-block:: bash salt '*' jenkins.delete_job jobname ''' if not name: raise SaltInvocationError('Required parameter \'name\' is missing') server = _connect() if not job_exists(name): raise CommandExecutionError('Job \'{0}\' does not exist'.format(name)) try: server.delete_job(name) except jenkins.JenkinsException as err: raise CommandExecutionError( 'Encountered error deleting job \'{0}\': {1}'.format(name, err) ) return True def enable_job(name=None): ''' Return true is job is enabled successfully. :param name: The name of the job to enable. :return: Return true if job is enabled successfully. CLI Example: .. code-block:: bash salt '*' jenkins.enable_job jobname ''' if not name: raise SaltInvocationError('Required parameter \'name\' is missing') server = _connect() if not job_exists(name): raise CommandExecutionError('Job \'{0}\' does not exist'.format(name)) try: server.enable_job(name) except jenkins.JenkinsException as err: raise CommandExecutionError( 'Encountered error enabling job \'{0}\': {1}'.format(name, err) ) return True def disable_job(name=None): ''' Return true is job is disabled successfully. :param name: The name of the job to disable. :return: Return true if job is disabled successfully. CLI Example: .. code-block:: bash salt '*' jenkins.disable_job jobname ''' if not name: raise SaltInvocationError('Required parameter \'name\' is missing') server = _connect() if not job_exists(name): raise CommandExecutionError('Job \'{0}\' does not exist'.format(name)) try: server.disable_job(name) except jenkins.JenkinsException as err: raise CommandExecutionError( 'Encountered error disabling job \'{0}\': {1}'.format(name, err) ) return True def job_status(name=None): ''' Return the current status, enabled or disabled, of the job. :param name: The name of the job to return status for :return: Return true if enabled or false if disabled. CLI Example: .. code-block:: bash salt '*' jenkins.job_status jobname ''' if not name: raise SaltInvocationError('Required parameter \'name\' is missing') server = _connect() if not job_exists(name): raise CommandExecutionError('Job \'{0}\' does not exist'.format(name)) return server.get_job_info('empty')['buildable'] def get_job_config(name=None): ''' Return the current job configuration for the provided job. :param name: The name of the job to return the configuration for. :return: The configuration for the job specified. CLI Example: .. code-block:: bash salt '*' jenkins.get_job_config jobname ''' if not name: raise SaltInvocationError('Required parameter \'name\' is missing') server = _connect() if not job_exists(name): raise CommandExecutionError('Job \'{0}\' does not exist'.format(name)) job_info = server.get_job_config(name) return job_info
saltstack/salt
salt/modules/azurearm_dns.py
record_set_create_or_update
python
def record_set_create_or_update(name, zone_name, resource_group, record_type, **kwargs): ''' .. versionadded:: Fluorine Creates or updates a record set within a DNS zone. :param name: The name of the record set, relative to the name of the zone. :param zone_name: The name of the DNS zone (without a terminating dot). :param resource_group: The name of the resource group. :param record_type: The type of DNS record in this record set. Record sets of type SOA can be updated but not created (they are created when the DNS zone is created). Possible values include: 'A', 'AAAA', 'CAA', 'CNAME', 'MX', 'NS', 'PTR', 'SOA', 'SRV', 'TXT' CLI Example: .. code-block:: bash salt-call azurearm_dns.record_set_create_or_update myhost myzone testgroup A arecords='[{ipv4_address: 10.0.0.1}]' ttl=300 ''' dnsconn = __utils__['azurearm.get_client']('dns', **kwargs) try: record_set_model = __utils__['azurearm.create_object_model']('dns', 'RecordSet', **kwargs) except TypeError as exc: result = {'error': 'The object model could not be built. ({0})'.format(str(exc))} return result try: record_set = dnsconn.record_sets.create_or_update( relative_record_set_name=name, zone_name=zone_name, resource_group_name=resource_group, record_type=record_type, parameters=record_set_model, if_match=kwargs.get('if_match'), if_none_match=kwargs.get('if_none_match') ) result = record_set.as_dict() except CloudError as exc: __utils__['azurearm.log_cloud_error']('dns', str(exc), **kwargs) result = {'error': str(exc)} except SerializationError as exc: result = {'error': 'The object model could not be parsed. ({0})'.format(str(exc))} return result
.. versionadded:: Fluorine Creates or updates a record set within a DNS zone. :param name: The name of the record set, relative to the name of the zone. :param zone_name: The name of the DNS zone (without a terminating dot). :param resource_group: The name of the resource group. :param record_type: The type of DNS record in this record set. Record sets of type SOA can be updated but not created (they are created when the DNS zone is created). Possible values include: 'A', 'AAAA', 'CAA', 'CNAME', 'MX', 'NS', 'PTR', 'SOA', 'SRV', 'TXT' CLI Example: .. code-block:: bash salt-call azurearm_dns.record_set_create_or_update myhost myzone testgroup A arecords='[{ipv4_address: 10.0.0.1}]' ttl=300
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/azurearm_dns.py#L81-L130
null
# -*- coding: utf-8 -*- ''' Azure (ARM) DNS Execution Module .. versionadded:: Fluorine :maintainer: <nicholasmhughes@gmail.com> :maturity: new :depends: * `azure <https://pypi.python.org/pypi/azure>`_ >= 2.0.0 * `azure-common <https://pypi.python.org/pypi/azure-common>`_ >= 1.1.8 * `azure-mgmt <https://pypi.python.org/pypi/azure-mgmt>`_ >= 1.0.0 * `azure-mgmt-compute <https://pypi.python.org/pypi/azure-mgmt-compute>`_ >= 1.0.0 * `azure-mgmt-dns <https://pypi.python.org/pypi/azure-mgmt-dns>`_ >= 2.0.0rc1 * `azure-mgmt-network <https://pypi.python.org/pypi/azure-mgmt-network>`_ >= 1.7.1 * `azure-mgmt-resource <https://pypi.python.org/pypi/azure-mgmt-resource>`_ >= 1.1.0 * `azure-mgmt-storage <https://pypi.python.org/pypi/azure-mgmt-storage>`_ >= 1.0.0 * `azure-mgmt-web <https://pypi.python.org/pypi/azure-mgmt-web>`_ >= 0.32.0 * `azure-storage <https://pypi.python.org/pypi/azure-storage>`_ >= 0.34.3 * `msrestazure <https://pypi.python.org/pypi/msrestazure>`_ >= 0.4.21 :platform: linux :configuration: This module requires Azure Resource Manager credentials to be passed as keyword arguments to every function in order to work properly. Required provider parameters: if using username and password: * ``subscription_id`` * ``username`` * ``password`` if using a service principal: * ``subscription_id`` * ``tenant`` * ``client_id`` * ``secret`` Optional provider parameters: **cloud_environment**: Used to point the cloud driver to different API endpoints, such as Azure GovCloud. Possible values: * ``AZURE_PUBLIC_CLOUD`` (default) * ``AZURE_CHINA_CLOUD`` * ``AZURE_US_GOV_CLOUD`` * ``AZURE_GERMAN_CLOUD`` ''' # Python libs from __future__ import absolute_import import logging # Azure libs HAS_LIBS = False try: import azure.mgmt.dns.models # pylint: disable=unused-import from msrest.exceptions import SerializationError from msrestazure.azure_exceptions import CloudError HAS_LIBS = True except ImportError: pass __virtualname__ = 'azurearm_dns' log = logging.getLogger(__name__) def __virtual__(): if not HAS_LIBS: return ( False, 'The following dependencies are required to use the AzureARM modules: ' 'Microsoft Azure SDK for Python >= 2.0rc6, ' 'MS REST Azure (msrestazure) >= 0.4' ) return __virtualname__ def record_set_delete(name, zone_name, resource_group, record_type, **kwargs): ''' .. versionadded:: Fluorine Deletes a record set from a DNS zone. This operation cannot be undone. :param name: The name of the record set, relative to the name of the zone. :param zone_name: The name of the DNS zone (without a terminating dot). :param resource_group: The name of the resource group. :param record_type: The type of DNS record in this record set. Record sets of type SOA cannot be deleted (they are deleted when the DNS zone is deleted). Possible values include: 'A', 'AAAA', 'CAA', 'CNAME', 'MX', 'NS', 'PTR', 'SOA', 'SRV', 'TXT' CLI Example: .. code-block:: bash salt-call azurearm_dns.record_set_delete myhost myzone testgroup A ''' result = False dnsconn = __utils__['azurearm.get_client']('dns', **kwargs) try: record_set = dnsconn.record_sets.delete( relative_record_set_name=name, zone_name=zone_name, resource_group_name=resource_group, record_type=record_type, if_match=kwargs.get('if_match') ) result = True except CloudError as exc: __utils__['azurearm.log_cloud_error']('dns', str(exc), **kwargs) return result def record_set_get(name, zone_name, resource_group, record_type, **kwargs): ''' .. versionadded:: Fluorine Get a dictionary representing a record set's properties. :param name: The name of the record set, relative to the name of the zone. :param zone_name: The name of the DNS zone (without a terminating dot). :param resource_group: The name of the resource group. :param record_type: The type of DNS record in this record set. Possible values include: 'A', 'AAAA', 'CAA', 'CNAME', 'MX', 'NS', 'PTR', 'SOA', 'SRV', 'TXT' CLI Example: .. code-block:: bash salt-call azurearm_dns.record_set_get '@' myzone testgroup SOA ''' dnsconn = __utils__['azurearm.get_client']('dns', **kwargs) try: record_set = dnsconn.record_sets.get( relative_record_set_name=name, zone_name=zone_name, resource_group_name=resource_group, record_type=record_type ) result = record_set.as_dict() except CloudError as exc: __utils__['azurearm.log_cloud_error']('dns', str(exc), **kwargs) result = {'error': str(exc)} return result def record_sets_list_by_type(zone_name, resource_group, record_type, top=None, recordsetnamesuffix=None, **kwargs): ''' .. versionadded:: Fluorine Lists the record sets of a specified type in a DNS zone. :param zone_name: The name of the DNS zone (without a terminating dot). :param resource_group: The name of the resource group. :param record_type: The type of record sets to enumerate. Possible values include: 'A', 'AAAA', 'CAA', 'CNAME', 'MX', 'NS', 'PTR', 'SOA', 'SRV', 'TXT' :param top: The maximum number of record sets to return. If not specified, returns up to 100 record sets. :param recordsetnamesuffix: The suffix label of the record set name that has to be used to filter the record set enumerations. CLI Example: .. code-block:: bash salt-call azurearm_dns.record_sets_list_by_type myzone testgroup SOA ''' result = {} dnsconn = __utils__['azurearm.get_client']('dns', **kwargs) try: record_sets = __utils__['azurearm.paged_object_to_list']( dnsconn.record_sets.list_by_type( zone_name=zone_name, resource_group_name=resource_group, record_type=record_type, top=top, recordsetnamesuffix=recordsetnamesuffix ) ) for record_set in record_sets: result[record_set['name']] = record_set except CloudError as exc: __utils__['azurearm.log_cloud_error']('dns', str(exc), **kwargs) result = {'error': str(exc)} return result def record_sets_list_by_dns_zone(zone_name, resource_group, top=None, recordsetnamesuffix=None, **kwargs): ''' .. versionadded:: Fluorine Lists all record sets in a DNS zone. :param zone_name: The name of the DNS zone (without a terminating dot). :param resource_group: The name of the resource group. :param top: The maximum number of record sets to return. If not specified, returns up to 100 record sets. :param recordsetnamesuffix: The suffix label of the record set name that has to be used to filter the record set enumerations. CLI Example: .. code-block:: bash salt-call azurearm_dns.record_sets_list_by_dns_zone myzone testgroup ''' result = {} dnsconn = __utils__['azurearm.get_client']('dns', **kwargs) try: record_sets = __utils__['azurearm.paged_object_to_list']( dnsconn.record_sets.list_by_dns_zone( zone_name=zone_name, resource_group_name=resource_group, top=top, recordsetnamesuffix=recordsetnamesuffix ) ) for record_set in record_sets: result[record_set['name']] = record_set except CloudError as exc: __utils__['azurearm.log_cloud_error']('dns', str(exc), **kwargs) result = {'error': str(exc)} return result def zone_create_or_update(name, resource_group, **kwargs): ''' .. versionadded:: Fluorine Creates or updates a DNS zone. Does not modify DNS records within the zone. :param name: The name of the DNS zone to create (without a terminating dot). :param resource_group: The name of the resource group. CLI Example: .. code-block:: bash salt-call azurearm_dns.zone_create_or_update myzone testgroup ''' # DNS zones are global objects kwargs['location'] = 'global' dnsconn = __utils__['azurearm.get_client']('dns', **kwargs) # Convert list of ID strings to list of dictionaries with id key. if isinstance(kwargs.get('registration_virtual_networks'), list): kwargs['registration_virtual_networks'] = [{'id': vnet} for vnet in kwargs['registration_virtual_networks']] if isinstance(kwargs.get('resolution_virtual_networks'), list): kwargs['resolution_virtual_networks'] = [{'id': vnet} for vnet in kwargs['resolution_virtual_networks']] try: zone_model = __utils__['azurearm.create_object_model']('dns', 'Zone', **kwargs) except TypeError as exc: result = {'error': 'The object model could not be built. ({0})'.format(str(exc))} return result try: zone = dnsconn.zones.create_or_update( zone_name=name, resource_group_name=resource_group, parameters=zone_model, if_match=kwargs.get('if_match'), if_none_match=kwargs.get('if_none_match') ) result = zone.as_dict() except CloudError as exc: __utils__['azurearm.log_cloud_error']('dns', str(exc), **kwargs) result = {'error': str(exc)} except SerializationError as exc: result = {'error': 'The object model could not be parsed. ({0})'.format(str(exc))} return result def zone_delete(name, resource_group, **kwargs): ''' .. versionadded:: Fluorine Delete a DNS zone within a resource group. :param name: The name of the DNS zone to delete. :param resource_group: The name of the resource group. CLI Example: .. code-block:: bash salt-call azurearm_dns.zone_delete myzone testgroup ''' result = False dnsconn = __utils__['azurearm.get_client']('dns', **kwargs) try: zone = dnsconn.zones.delete( zone_name=name, resource_group_name=resource_group, if_match=kwargs.get('if_match') ) zone.wait() result = True except CloudError as exc: __utils__['azurearm.log_cloud_error']('dns', str(exc), **kwargs) return result def zone_get(name, resource_group, **kwargs): ''' .. versionadded:: Fluorine Get a dictionary representing a DNS zone's properties, but not the record sets within the zone. :param name: The DNS zone to get. :param resource_group: The name of the resource group. CLI Example: .. code-block:: bash salt-call azurearm_dns.zone_get myzone testgroup ''' dnsconn = __utils__['azurearm.get_client']('dns', **kwargs) try: zone = dnsconn.zones.get( zone_name=name, resource_group_name=resource_group ) result = zone.as_dict() except CloudError as exc: __utils__['azurearm.log_cloud_error']('dns', str(exc), **kwargs) result = {'error': str(exc)} return result def zones_list_by_resource_group(resource_group, top=None, **kwargs): ''' .. versionadded:: Fluorine Lists the DNS zones in a resource group. :param resource_group: The name of the resource group. :param top: The maximum number of DNS zones to return. If not specified, returns up to 100 zones. CLI Example: .. code-block:: bash salt-call azurearm_dns.zones_list_by_resource_group testgroup ''' result = {} dnsconn = __utils__['azurearm.get_client']('dns', **kwargs) try: zones = __utils__['azurearm.paged_object_to_list']( dnsconn.zones.list_by_resource_group( resource_group_name=resource_group, top=top ) ) for zone in zones: result[zone['name']] = zone except CloudError as exc: __utils__['azurearm.log_cloud_error']('dns', str(exc), **kwargs) result = {'error': str(exc)} return result def zones_list(top=None, **kwargs): ''' .. versionadded:: Fluorine Lists the DNS zones in all resource groups in a subscription. :param top: The maximum number of DNS zones to return. If not specified, returns up to 100 zones. CLI Example: .. code-block:: bash salt-call azurearm_dns.zones_list ''' result = {} dnsconn = __utils__['azurearm.get_client']('dns', **kwargs) try: zones = __utils__['azurearm.paged_object_to_list'](dnsconn.zones.list(top=top)) for zone in zones: result[zone['name']] = zone except CloudError as exc: __utils__['azurearm.log_cloud_error']('dns', str(exc), **kwargs) result = {'error': str(exc)} return result
saltstack/salt
salt/modules/azurearm_dns.py
record_set_delete
python
def record_set_delete(name, zone_name, resource_group, record_type, **kwargs): ''' .. versionadded:: Fluorine Deletes a record set from a DNS zone. This operation cannot be undone. :param name: The name of the record set, relative to the name of the zone. :param zone_name: The name of the DNS zone (without a terminating dot). :param resource_group: The name of the resource group. :param record_type: The type of DNS record in this record set. Record sets of type SOA cannot be deleted (they are deleted when the DNS zone is deleted). Possible values include: 'A', 'AAAA', 'CAA', 'CNAME', 'MX', 'NS', 'PTR', 'SOA', 'SRV', 'TXT' CLI Example: .. code-block:: bash salt-call azurearm_dns.record_set_delete myhost myzone testgroup A ''' result = False dnsconn = __utils__['azurearm.get_client']('dns', **kwargs) try: record_set = dnsconn.record_sets.delete( relative_record_set_name=name, zone_name=zone_name, resource_group_name=resource_group, record_type=record_type, if_match=kwargs.get('if_match') ) result = True except CloudError as exc: __utils__['azurearm.log_cloud_error']('dns', str(exc), **kwargs) return result
.. versionadded:: Fluorine Deletes a record set from a DNS zone. This operation cannot be undone. :param name: The name of the record set, relative to the name of the zone. :param zone_name: The name of the DNS zone (without a terminating dot). :param resource_group: The name of the resource group. :param record_type: The type of DNS record in this record set. Record sets of type SOA cannot be deleted (they are deleted when the DNS zone is deleted). Possible values include: 'A', 'AAAA', 'CAA', 'CNAME', 'MX', 'NS', 'PTR', 'SOA', 'SRV', 'TXT' CLI Example: .. code-block:: bash salt-call azurearm_dns.record_set_delete myhost myzone testgroup A
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/azurearm_dns.py#L133-L170
null
# -*- coding: utf-8 -*- ''' Azure (ARM) DNS Execution Module .. versionadded:: Fluorine :maintainer: <nicholasmhughes@gmail.com> :maturity: new :depends: * `azure <https://pypi.python.org/pypi/azure>`_ >= 2.0.0 * `azure-common <https://pypi.python.org/pypi/azure-common>`_ >= 1.1.8 * `azure-mgmt <https://pypi.python.org/pypi/azure-mgmt>`_ >= 1.0.0 * `azure-mgmt-compute <https://pypi.python.org/pypi/azure-mgmt-compute>`_ >= 1.0.0 * `azure-mgmt-dns <https://pypi.python.org/pypi/azure-mgmt-dns>`_ >= 2.0.0rc1 * `azure-mgmt-network <https://pypi.python.org/pypi/azure-mgmt-network>`_ >= 1.7.1 * `azure-mgmt-resource <https://pypi.python.org/pypi/azure-mgmt-resource>`_ >= 1.1.0 * `azure-mgmt-storage <https://pypi.python.org/pypi/azure-mgmt-storage>`_ >= 1.0.0 * `azure-mgmt-web <https://pypi.python.org/pypi/azure-mgmt-web>`_ >= 0.32.0 * `azure-storage <https://pypi.python.org/pypi/azure-storage>`_ >= 0.34.3 * `msrestazure <https://pypi.python.org/pypi/msrestazure>`_ >= 0.4.21 :platform: linux :configuration: This module requires Azure Resource Manager credentials to be passed as keyword arguments to every function in order to work properly. Required provider parameters: if using username and password: * ``subscription_id`` * ``username`` * ``password`` if using a service principal: * ``subscription_id`` * ``tenant`` * ``client_id`` * ``secret`` Optional provider parameters: **cloud_environment**: Used to point the cloud driver to different API endpoints, such as Azure GovCloud. Possible values: * ``AZURE_PUBLIC_CLOUD`` (default) * ``AZURE_CHINA_CLOUD`` * ``AZURE_US_GOV_CLOUD`` * ``AZURE_GERMAN_CLOUD`` ''' # Python libs from __future__ import absolute_import import logging # Azure libs HAS_LIBS = False try: import azure.mgmt.dns.models # pylint: disable=unused-import from msrest.exceptions import SerializationError from msrestazure.azure_exceptions import CloudError HAS_LIBS = True except ImportError: pass __virtualname__ = 'azurearm_dns' log = logging.getLogger(__name__) def __virtual__(): if not HAS_LIBS: return ( False, 'The following dependencies are required to use the AzureARM modules: ' 'Microsoft Azure SDK for Python >= 2.0rc6, ' 'MS REST Azure (msrestazure) >= 0.4' ) return __virtualname__ def record_set_create_or_update(name, zone_name, resource_group, record_type, **kwargs): ''' .. versionadded:: Fluorine Creates or updates a record set within a DNS zone. :param name: The name of the record set, relative to the name of the zone. :param zone_name: The name of the DNS zone (without a terminating dot). :param resource_group: The name of the resource group. :param record_type: The type of DNS record in this record set. Record sets of type SOA can be updated but not created (they are created when the DNS zone is created). Possible values include: 'A', 'AAAA', 'CAA', 'CNAME', 'MX', 'NS', 'PTR', 'SOA', 'SRV', 'TXT' CLI Example: .. code-block:: bash salt-call azurearm_dns.record_set_create_or_update myhost myzone testgroup A arecords='[{ipv4_address: 10.0.0.1}]' ttl=300 ''' dnsconn = __utils__['azurearm.get_client']('dns', **kwargs) try: record_set_model = __utils__['azurearm.create_object_model']('dns', 'RecordSet', **kwargs) except TypeError as exc: result = {'error': 'The object model could not be built. ({0})'.format(str(exc))} return result try: record_set = dnsconn.record_sets.create_or_update( relative_record_set_name=name, zone_name=zone_name, resource_group_name=resource_group, record_type=record_type, parameters=record_set_model, if_match=kwargs.get('if_match'), if_none_match=kwargs.get('if_none_match') ) result = record_set.as_dict() except CloudError as exc: __utils__['azurearm.log_cloud_error']('dns', str(exc), **kwargs) result = {'error': str(exc)} except SerializationError as exc: result = {'error': 'The object model could not be parsed. ({0})'.format(str(exc))} return result def record_set_get(name, zone_name, resource_group, record_type, **kwargs): ''' .. versionadded:: Fluorine Get a dictionary representing a record set's properties. :param name: The name of the record set, relative to the name of the zone. :param zone_name: The name of the DNS zone (without a terminating dot). :param resource_group: The name of the resource group. :param record_type: The type of DNS record in this record set. Possible values include: 'A', 'AAAA', 'CAA', 'CNAME', 'MX', 'NS', 'PTR', 'SOA', 'SRV', 'TXT' CLI Example: .. code-block:: bash salt-call azurearm_dns.record_set_get '@' myzone testgroup SOA ''' dnsconn = __utils__['azurearm.get_client']('dns', **kwargs) try: record_set = dnsconn.record_sets.get( relative_record_set_name=name, zone_name=zone_name, resource_group_name=resource_group, record_type=record_type ) result = record_set.as_dict() except CloudError as exc: __utils__['azurearm.log_cloud_error']('dns', str(exc), **kwargs) result = {'error': str(exc)} return result def record_sets_list_by_type(zone_name, resource_group, record_type, top=None, recordsetnamesuffix=None, **kwargs): ''' .. versionadded:: Fluorine Lists the record sets of a specified type in a DNS zone. :param zone_name: The name of the DNS zone (without a terminating dot). :param resource_group: The name of the resource group. :param record_type: The type of record sets to enumerate. Possible values include: 'A', 'AAAA', 'CAA', 'CNAME', 'MX', 'NS', 'PTR', 'SOA', 'SRV', 'TXT' :param top: The maximum number of record sets to return. If not specified, returns up to 100 record sets. :param recordsetnamesuffix: The suffix label of the record set name that has to be used to filter the record set enumerations. CLI Example: .. code-block:: bash salt-call azurearm_dns.record_sets_list_by_type myzone testgroup SOA ''' result = {} dnsconn = __utils__['azurearm.get_client']('dns', **kwargs) try: record_sets = __utils__['azurearm.paged_object_to_list']( dnsconn.record_sets.list_by_type( zone_name=zone_name, resource_group_name=resource_group, record_type=record_type, top=top, recordsetnamesuffix=recordsetnamesuffix ) ) for record_set in record_sets: result[record_set['name']] = record_set except CloudError as exc: __utils__['azurearm.log_cloud_error']('dns', str(exc), **kwargs) result = {'error': str(exc)} return result def record_sets_list_by_dns_zone(zone_name, resource_group, top=None, recordsetnamesuffix=None, **kwargs): ''' .. versionadded:: Fluorine Lists all record sets in a DNS zone. :param zone_name: The name of the DNS zone (without a terminating dot). :param resource_group: The name of the resource group. :param top: The maximum number of record sets to return. If not specified, returns up to 100 record sets. :param recordsetnamesuffix: The suffix label of the record set name that has to be used to filter the record set enumerations. CLI Example: .. code-block:: bash salt-call azurearm_dns.record_sets_list_by_dns_zone myzone testgroup ''' result = {} dnsconn = __utils__['azurearm.get_client']('dns', **kwargs) try: record_sets = __utils__['azurearm.paged_object_to_list']( dnsconn.record_sets.list_by_dns_zone( zone_name=zone_name, resource_group_name=resource_group, top=top, recordsetnamesuffix=recordsetnamesuffix ) ) for record_set in record_sets: result[record_set['name']] = record_set except CloudError as exc: __utils__['azurearm.log_cloud_error']('dns', str(exc), **kwargs) result = {'error': str(exc)} return result def zone_create_or_update(name, resource_group, **kwargs): ''' .. versionadded:: Fluorine Creates or updates a DNS zone. Does not modify DNS records within the zone. :param name: The name of the DNS zone to create (without a terminating dot). :param resource_group: The name of the resource group. CLI Example: .. code-block:: bash salt-call azurearm_dns.zone_create_or_update myzone testgroup ''' # DNS zones are global objects kwargs['location'] = 'global' dnsconn = __utils__['azurearm.get_client']('dns', **kwargs) # Convert list of ID strings to list of dictionaries with id key. if isinstance(kwargs.get('registration_virtual_networks'), list): kwargs['registration_virtual_networks'] = [{'id': vnet} for vnet in kwargs['registration_virtual_networks']] if isinstance(kwargs.get('resolution_virtual_networks'), list): kwargs['resolution_virtual_networks'] = [{'id': vnet} for vnet in kwargs['resolution_virtual_networks']] try: zone_model = __utils__['azurearm.create_object_model']('dns', 'Zone', **kwargs) except TypeError as exc: result = {'error': 'The object model could not be built. ({0})'.format(str(exc))} return result try: zone = dnsconn.zones.create_or_update( zone_name=name, resource_group_name=resource_group, parameters=zone_model, if_match=kwargs.get('if_match'), if_none_match=kwargs.get('if_none_match') ) result = zone.as_dict() except CloudError as exc: __utils__['azurearm.log_cloud_error']('dns', str(exc), **kwargs) result = {'error': str(exc)} except SerializationError as exc: result = {'error': 'The object model could not be parsed. ({0})'.format(str(exc))} return result def zone_delete(name, resource_group, **kwargs): ''' .. versionadded:: Fluorine Delete a DNS zone within a resource group. :param name: The name of the DNS zone to delete. :param resource_group: The name of the resource group. CLI Example: .. code-block:: bash salt-call azurearm_dns.zone_delete myzone testgroup ''' result = False dnsconn = __utils__['azurearm.get_client']('dns', **kwargs) try: zone = dnsconn.zones.delete( zone_name=name, resource_group_name=resource_group, if_match=kwargs.get('if_match') ) zone.wait() result = True except CloudError as exc: __utils__['azurearm.log_cloud_error']('dns', str(exc), **kwargs) return result def zone_get(name, resource_group, **kwargs): ''' .. versionadded:: Fluorine Get a dictionary representing a DNS zone's properties, but not the record sets within the zone. :param name: The DNS zone to get. :param resource_group: The name of the resource group. CLI Example: .. code-block:: bash salt-call azurearm_dns.zone_get myzone testgroup ''' dnsconn = __utils__['azurearm.get_client']('dns', **kwargs) try: zone = dnsconn.zones.get( zone_name=name, resource_group_name=resource_group ) result = zone.as_dict() except CloudError as exc: __utils__['azurearm.log_cloud_error']('dns', str(exc), **kwargs) result = {'error': str(exc)} return result def zones_list_by_resource_group(resource_group, top=None, **kwargs): ''' .. versionadded:: Fluorine Lists the DNS zones in a resource group. :param resource_group: The name of the resource group. :param top: The maximum number of DNS zones to return. If not specified, returns up to 100 zones. CLI Example: .. code-block:: bash salt-call azurearm_dns.zones_list_by_resource_group testgroup ''' result = {} dnsconn = __utils__['azurearm.get_client']('dns', **kwargs) try: zones = __utils__['azurearm.paged_object_to_list']( dnsconn.zones.list_by_resource_group( resource_group_name=resource_group, top=top ) ) for zone in zones: result[zone['name']] = zone except CloudError as exc: __utils__['azurearm.log_cloud_error']('dns', str(exc), **kwargs) result = {'error': str(exc)} return result def zones_list(top=None, **kwargs): ''' .. versionadded:: Fluorine Lists the DNS zones in all resource groups in a subscription. :param top: The maximum number of DNS zones to return. If not specified, returns up to 100 zones. CLI Example: .. code-block:: bash salt-call azurearm_dns.zones_list ''' result = {} dnsconn = __utils__['azurearm.get_client']('dns', **kwargs) try: zones = __utils__['azurearm.paged_object_to_list'](dnsconn.zones.list(top=top)) for zone in zones: result[zone['name']] = zone except CloudError as exc: __utils__['azurearm.log_cloud_error']('dns', str(exc), **kwargs) result = {'error': str(exc)} return result
saltstack/salt
salt/modules/azurearm_dns.py
record_set_get
python
def record_set_get(name, zone_name, resource_group, record_type, **kwargs): ''' .. versionadded:: Fluorine Get a dictionary representing a record set's properties. :param name: The name of the record set, relative to the name of the zone. :param zone_name: The name of the DNS zone (without a terminating dot). :param resource_group: The name of the resource group. :param record_type: The type of DNS record in this record set. Possible values include: 'A', 'AAAA', 'CAA', 'CNAME', 'MX', 'NS', 'PTR', 'SOA', 'SRV', 'TXT' CLI Example: .. code-block:: bash salt-call azurearm_dns.record_set_get '@' myzone testgroup SOA ''' dnsconn = __utils__['azurearm.get_client']('dns', **kwargs) try: record_set = dnsconn.record_sets.get( relative_record_set_name=name, zone_name=zone_name, resource_group_name=resource_group, record_type=record_type ) result = record_set.as_dict() except CloudError as exc: __utils__['azurearm.log_cloud_error']('dns', str(exc), **kwargs) result = {'error': str(exc)} return result
.. versionadded:: Fluorine Get a dictionary representing a record set's properties. :param name: The name of the record set, relative to the name of the zone. :param zone_name: The name of the DNS zone (without a terminating dot). :param resource_group: The name of the resource group. :param record_type: The type of DNS record in this record set. Possible values include: 'A', 'AAAA', 'CAA', 'CNAME', 'MX', 'NS', 'PTR', 'SOA', 'SRV', 'TXT' CLI Example: .. code-block:: bash salt-call azurearm_dns.record_set_get '@' myzone testgroup SOA
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/azurearm_dns.py#L173-L209
null
# -*- coding: utf-8 -*- ''' Azure (ARM) DNS Execution Module .. versionadded:: Fluorine :maintainer: <nicholasmhughes@gmail.com> :maturity: new :depends: * `azure <https://pypi.python.org/pypi/azure>`_ >= 2.0.0 * `azure-common <https://pypi.python.org/pypi/azure-common>`_ >= 1.1.8 * `azure-mgmt <https://pypi.python.org/pypi/azure-mgmt>`_ >= 1.0.0 * `azure-mgmt-compute <https://pypi.python.org/pypi/azure-mgmt-compute>`_ >= 1.0.0 * `azure-mgmt-dns <https://pypi.python.org/pypi/azure-mgmt-dns>`_ >= 2.0.0rc1 * `azure-mgmt-network <https://pypi.python.org/pypi/azure-mgmt-network>`_ >= 1.7.1 * `azure-mgmt-resource <https://pypi.python.org/pypi/azure-mgmt-resource>`_ >= 1.1.0 * `azure-mgmt-storage <https://pypi.python.org/pypi/azure-mgmt-storage>`_ >= 1.0.0 * `azure-mgmt-web <https://pypi.python.org/pypi/azure-mgmt-web>`_ >= 0.32.0 * `azure-storage <https://pypi.python.org/pypi/azure-storage>`_ >= 0.34.3 * `msrestazure <https://pypi.python.org/pypi/msrestazure>`_ >= 0.4.21 :platform: linux :configuration: This module requires Azure Resource Manager credentials to be passed as keyword arguments to every function in order to work properly. Required provider parameters: if using username and password: * ``subscription_id`` * ``username`` * ``password`` if using a service principal: * ``subscription_id`` * ``tenant`` * ``client_id`` * ``secret`` Optional provider parameters: **cloud_environment**: Used to point the cloud driver to different API endpoints, such as Azure GovCloud. Possible values: * ``AZURE_PUBLIC_CLOUD`` (default) * ``AZURE_CHINA_CLOUD`` * ``AZURE_US_GOV_CLOUD`` * ``AZURE_GERMAN_CLOUD`` ''' # Python libs from __future__ import absolute_import import logging # Azure libs HAS_LIBS = False try: import azure.mgmt.dns.models # pylint: disable=unused-import from msrest.exceptions import SerializationError from msrestazure.azure_exceptions import CloudError HAS_LIBS = True except ImportError: pass __virtualname__ = 'azurearm_dns' log = logging.getLogger(__name__) def __virtual__(): if not HAS_LIBS: return ( False, 'The following dependencies are required to use the AzureARM modules: ' 'Microsoft Azure SDK for Python >= 2.0rc6, ' 'MS REST Azure (msrestazure) >= 0.4' ) return __virtualname__ def record_set_create_or_update(name, zone_name, resource_group, record_type, **kwargs): ''' .. versionadded:: Fluorine Creates or updates a record set within a DNS zone. :param name: The name of the record set, relative to the name of the zone. :param zone_name: The name of the DNS zone (without a terminating dot). :param resource_group: The name of the resource group. :param record_type: The type of DNS record in this record set. Record sets of type SOA can be updated but not created (they are created when the DNS zone is created). Possible values include: 'A', 'AAAA', 'CAA', 'CNAME', 'MX', 'NS', 'PTR', 'SOA', 'SRV', 'TXT' CLI Example: .. code-block:: bash salt-call azurearm_dns.record_set_create_or_update myhost myzone testgroup A arecords='[{ipv4_address: 10.0.0.1}]' ttl=300 ''' dnsconn = __utils__['azurearm.get_client']('dns', **kwargs) try: record_set_model = __utils__['azurearm.create_object_model']('dns', 'RecordSet', **kwargs) except TypeError as exc: result = {'error': 'The object model could not be built. ({0})'.format(str(exc))} return result try: record_set = dnsconn.record_sets.create_or_update( relative_record_set_name=name, zone_name=zone_name, resource_group_name=resource_group, record_type=record_type, parameters=record_set_model, if_match=kwargs.get('if_match'), if_none_match=kwargs.get('if_none_match') ) result = record_set.as_dict() except CloudError as exc: __utils__['azurearm.log_cloud_error']('dns', str(exc), **kwargs) result = {'error': str(exc)} except SerializationError as exc: result = {'error': 'The object model could not be parsed. ({0})'.format(str(exc))} return result def record_set_delete(name, zone_name, resource_group, record_type, **kwargs): ''' .. versionadded:: Fluorine Deletes a record set from a DNS zone. This operation cannot be undone. :param name: The name of the record set, relative to the name of the zone. :param zone_name: The name of the DNS zone (without a terminating dot). :param resource_group: The name of the resource group. :param record_type: The type of DNS record in this record set. Record sets of type SOA cannot be deleted (they are deleted when the DNS zone is deleted). Possible values include: 'A', 'AAAA', 'CAA', 'CNAME', 'MX', 'NS', 'PTR', 'SOA', 'SRV', 'TXT' CLI Example: .. code-block:: bash salt-call azurearm_dns.record_set_delete myhost myzone testgroup A ''' result = False dnsconn = __utils__['azurearm.get_client']('dns', **kwargs) try: record_set = dnsconn.record_sets.delete( relative_record_set_name=name, zone_name=zone_name, resource_group_name=resource_group, record_type=record_type, if_match=kwargs.get('if_match') ) result = True except CloudError as exc: __utils__['azurearm.log_cloud_error']('dns', str(exc), **kwargs) return result def record_sets_list_by_type(zone_name, resource_group, record_type, top=None, recordsetnamesuffix=None, **kwargs): ''' .. versionadded:: Fluorine Lists the record sets of a specified type in a DNS zone. :param zone_name: The name of the DNS zone (without a terminating dot). :param resource_group: The name of the resource group. :param record_type: The type of record sets to enumerate. Possible values include: 'A', 'AAAA', 'CAA', 'CNAME', 'MX', 'NS', 'PTR', 'SOA', 'SRV', 'TXT' :param top: The maximum number of record sets to return. If not specified, returns up to 100 record sets. :param recordsetnamesuffix: The suffix label of the record set name that has to be used to filter the record set enumerations. CLI Example: .. code-block:: bash salt-call azurearm_dns.record_sets_list_by_type myzone testgroup SOA ''' result = {} dnsconn = __utils__['azurearm.get_client']('dns', **kwargs) try: record_sets = __utils__['azurearm.paged_object_to_list']( dnsconn.record_sets.list_by_type( zone_name=zone_name, resource_group_name=resource_group, record_type=record_type, top=top, recordsetnamesuffix=recordsetnamesuffix ) ) for record_set in record_sets: result[record_set['name']] = record_set except CloudError as exc: __utils__['azurearm.log_cloud_error']('dns', str(exc), **kwargs) result = {'error': str(exc)} return result def record_sets_list_by_dns_zone(zone_name, resource_group, top=None, recordsetnamesuffix=None, **kwargs): ''' .. versionadded:: Fluorine Lists all record sets in a DNS zone. :param zone_name: The name of the DNS zone (without a terminating dot). :param resource_group: The name of the resource group. :param top: The maximum number of record sets to return. If not specified, returns up to 100 record sets. :param recordsetnamesuffix: The suffix label of the record set name that has to be used to filter the record set enumerations. CLI Example: .. code-block:: bash salt-call azurearm_dns.record_sets_list_by_dns_zone myzone testgroup ''' result = {} dnsconn = __utils__['azurearm.get_client']('dns', **kwargs) try: record_sets = __utils__['azurearm.paged_object_to_list']( dnsconn.record_sets.list_by_dns_zone( zone_name=zone_name, resource_group_name=resource_group, top=top, recordsetnamesuffix=recordsetnamesuffix ) ) for record_set in record_sets: result[record_set['name']] = record_set except CloudError as exc: __utils__['azurearm.log_cloud_error']('dns', str(exc), **kwargs) result = {'error': str(exc)} return result def zone_create_or_update(name, resource_group, **kwargs): ''' .. versionadded:: Fluorine Creates or updates a DNS zone. Does not modify DNS records within the zone. :param name: The name of the DNS zone to create (without a terminating dot). :param resource_group: The name of the resource group. CLI Example: .. code-block:: bash salt-call azurearm_dns.zone_create_or_update myzone testgroup ''' # DNS zones are global objects kwargs['location'] = 'global' dnsconn = __utils__['azurearm.get_client']('dns', **kwargs) # Convert list of ID strings to list of dictionaries with id key. if isinstance(kwargs.get('registration_virtual_networks'), list): kwargs['registration_virtual_networks'] = [{'id': vnet} for vnet in kwargs['registration_virtual_networks']] if isinstance(kwargs.get('resolution_virtual_networks'), list): kwargs['resolution_virtual_networks'] = [{'id': vnet} for vnet in kwargs['resolution_virtual_networks']] try: zone_model = __utils__['azurearm.create_object_model']('dns', 'Zone', **kwargs) except TypeError as exc: result = {'error': 'The object model could not be built. ({0})'.format(str(exc))} return result try: zone = dnsconn.zones.create_or_update( zone_name=name, resource_group_name=resource_group, parameters=zone_model, if_match=kwargs.get('if_match'), if_none_match=kwargs.get('if_none_match') ) result = zone.as_dict() except CloudError as exc: __utils__['azurearm.log_cloud_error']('dns', str(exc), **kwargs) result = {'error': str(exc)} except SerializationError as exc: result = {'error': 'The object model could not be parsed. ({0})'.format(str(exc))} return result def zone_delete(name, resource_group, **kwargs): ''' .. versionadded:: Fluorine Delete a DNS zone within a resource group. :param name: The name of the DNS zone to delete. :param resource_group: The name of the resource group. CLI Example: .. code-block:: bash salt-call azurearm_dns.zone_delete myzone testgroup ''' result = False dnsconn = __utils__['azurearm.get_client']('dns', **kwargs) try: zone = dnsconn.zones.delete( zone_name=name, resource_group_name=resource_group, if_match=kwargs.get('if_match') ) zone.wait() result = True except CloudError as exc: __utils__['azurearm.log_cloud_error']('dns', str(exc), **kwargs) return result def zone_get(name, resource_group, **kwargs): ''' .. versionadded:: Fluorine Get a dictionary representing a DNS zone's properties, but not the record sets within the zone. :param name: The DNS zone to get. :param resource_group: The name of the resource group. CLI Example: .. code-block:: bash salt-call azurearm_dns.zone_get myzone testgroup ''' dnsconn = __utils__['azurearm.get_client']('dns', **kwargs) try: zone = dnsconn.zones.get( zone_name=name, resource_group_name=resource_group ) result = zone.as_dict() except CloudError as exc: __utils__['azurearm.log_cloud_error']('dns', str(exc), **kwargs) result = {'error': str(exc)} return result def zones_list_by_resource_group(resource_group, top=None, **kwargs): ''' .. versionadded:: Fluorine Lists the DNS zones in a resource group. :param resource_group: The name of the resource group. :param top: The maximum number of DNS zones to return. If not specified, returns up to 100 zones. CLI Example: .. code-block:: bash salt-call azurearm_dns.zones_list_by_resource_group testgroup ''' result = {} dnsconn = __utils__['azurearm.get_client']('dns', **kwargs) try: zones = __utils__['azurearm.paged_object_to_list']( dnsconn.zones.list_by_resource_group( resource_group_name=resource_group, top=top ) ) for zone in zones: result[zone['name']] = zone except CloudError as exc: __utils__['azurearm.log_cloud_error']('dns', str(exc), **kwargs) result = {'error': str(exc)} return result def zones_list(top=None, **kwargs): ''' .. versionadded:: Fluorine Lists the DNS zones in all resource groups in a subscription. :param top: The maximum number of DNS zones to return. If not specified, returns up to 100 zones. CLI Example: .. code-block:: bash salt-call azurearm_dns.zones_list ''' result = {} dnsconn = __utils__['azurearm.get_client']('dns', **kwargs) try: zones = __utils__['azurearm.paged_object_to_list'](dnsconn.zones.list(top=top)) for zone in zones: result[zone['name']] = zone except CloudError as exc: __utils__['azurearm.log_cloud_error']('dns', str(exc), **kwargs) result = {'error': str(exc)} return result
saltstack/salt
salt/modules/azurearm_dns.py
record_sets_list_by_type
python
def record_sets_list_by_type(zone_name, resource_group, record_type, top=None, recordsetnamesuffix=None, **kwargs): ''' .. versionadded:: Fluorine Lists the record sets of a specified type in a DNS zone. :param zone_name: The name of the DNS zone (without a terminating dot). :param resource_group: The name of the resource group. :param record_type: The type of record sets to enumerate. Possible values include: 'A', 'AAAA', 'CAA', 'CNAME', 'MX', 'NS', 'PTR', 'SOA', 'SRV', 'TXT' :param top: The maximum number of record sets to return. If not specified, returns up to 100 record sets. :param recordsetnamesuffix: The suffix label of the record set name that has to be used to filter the record set enumerations. CLI Example: .. code-block:: bash salt-call azurearm_dns.record_sets_list_by_type myzone testgroup SOA ''' result = {} dnsconn = __utils__['azurearm.get_client']('dns', **kwargs) try: record_sets = __utils__['azurearm.paged_object_to_list']( dnsconn.record_sets.list_by_type( zone_name=zone_name, resource_group_name=resource_group, record_type=record_type, top=top, recordsetnamesuffix=recordsetnamesuffix ) ) for record_set in record_sets: result[record_set['name']] = record_set except CloudError as exc: __utils__['azurearm.log_cloud_error']('dns', str(exc), **kwargs) result = {'error': str(exc)} return result
.. versionadded:: Fluorine Lists the record sets of a specified type in a DNS zone. :param zone_name: The name of the DNS zone (without a terminating dot). :param resource_group: The name of the resource group. :param record_type: The type of record sets to enumerate. Possible values include: 'A', 'AAAA', 'CAA', 'CNAME', 'MX', 'NS', 'PTR', 'SOA', 'SRV', 'TXT' :param top: The maximum number of record sets to return. If not specified, returns up to 100 record sets. :param recordsetnamesuffix: The suffix label of the record set name that has to be used to filter the record set enumerations. CLI Example: .. code-block:: bash salt-call azurearm_dns.record_sets_list_by_type myzone testgroup SOA
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/azurearm_dns.py#L212-L257
null
# -*- coding: utf-8 -*- ''' Azure (ARM) DNS Execution Module .. versionadded:: Fluorine :maintainer: <nicholasmhughes@gmail.com> :maturity: new :depends: * `azure <https://pypi.python.org/pypi/azure>`_ >= 2.0.0 * `azure-common <https://pypi.python.org/pypi/azure-common>`_ >= 1.1.8 * `azure-mgmt <https://pypi.python.org/pypi/azure-mgmt>`_ >= 1.0.0 * `azure-mgmt-compute <https://pypi.python.org/pypi/azure-mgmt-compute>`_ >= 1.0.0 * `azure-mgmt-dns <https://pypi.python.org/pypi/azure-mgmt-dns>`_ >= 2.0.0rc1 * `azure-mgmt-network <https://pypi.python.org/pypi/azure-mgmt-network>`_ >= 1.7.1 * `azure-mgmt-resource <https://pypi.python.org/pypi/azure-mgmt-resource>`_ >= 1.1.0 * `azure-mgmt-storage <https://pypi.python.org/pypi/azure-mgmt-storage>`_ >= 1.0.0 * `azure-mgmt-web <https://pypi.python.org/pypi/azure-mgmt-web>`_ >= 0.32.0 * `azure-storage <https://pypi.python.org/pypi/azure-storage>`_ >= 0.34.3 * `msrestazure <https://pypi.python.org/pypi/msrestazure>`_ >= 0.4.21 :platform: linux :configuration: This module requires Azure Resource Manager credentials to be passed as keyword arguments to every function in order to work properly. Required provider parameters: if using username and password: * ``subscription_id`` * ``username`` * ``password`` if using a service principal: * ``subscription_id`` * ``tenant`` * ``client_id`` * ``secret`` Optional provider parameters: **cloud_environment**: Used to point the cloud driver to different API endpoints, such as Azure GovCloud. Possible values: * ``AZURE_PUBLIC_CLOUD`` (default) * ``AZURE_CHINA_CLOUD`` * ``AZURE_US_GOV_CLOUD`` * ``AZURE_GERMAN_CLOUD`` ''' # Python libs from __future__ import absolute_import import logging # Azure libs HAS_LIBS = False try: import azure.mgmt.dns.models # pylint: disable=unused-import from msrest.exceptions import SerializationError from msrestazure.azure_exceptions import CloudError HAS_LIBS = True except ImportError: pass __virtualname__ = 'azurearm_dns' log = logging.getLogger(__name__) def __virtual__(): if not HAS_LIBS: return ( False, 'The following dependencies are required to use the AzureARM modules: ' 'Microsoft Azure SDK for Python >= 2.0rc6, ' 'MS REST Azure (msrestazure) >= 0.4' ) return __virtualname__ def record_set_create_or_update(name, zone_name, resource_group, record_type, **kwargs): ''' .. versionadded:: Fluorine Creates or updates a record set within a DNS zone. :param name: The name of the record set, relative to the name of the zone. :param zone_name: The name of the DNS zone (without a terminating dot). :param resource_group: The name of the resource group. :param record_type: The type of DNS record in this record set. Record sets of type SOA can be updated but not created (they are created when the DNS zone is created). Possible values include: 'A', 'AAAA', 'CAA', 'CNAME', 'MX', 'NS', 'PTR', 'SOA', 'SRV', 'TXT' CLI Example: .. code-block:: bash salt-call azurearm_dns.record_set_create_or_update myhost myzone testgroup A arecords='[{ipv4_address: 10.0.0.1}]' ttl=300 ''' dnsconn = __utils__['azurearm.get_client']('dns', **kwargs) try: record_set_model = __utils__['azurearm.create_object_model']('dns', 'RecordSet', **kwargs) except TypeError as exc: result = {'error': 'The object model could not be built. ({0})'.format(str(exc))} return result try: record_set = dnsconn.record_sets.create_or_update( relative_record_set_name=name, zone_name=zone_name, resource_group_name=resource_group, record_type=record_type, parameters=record_set_model, if_match=kwargs.get('if_match'), if_none_match=kwargs.get('if_none_match') ) result = record_set.as_dict() except CloudError as exc: __utils__['azurearm.log_cloud_error']('dns', str(exc), **kwargs) result = {'error': str(exc)} except SerializationError as exc: result = {'error': 'The object model could not be parsed. ({0})'.format(str(exc))} return result def record_set_delete(name, zone_name, resource_group, record_type, **kwargs): ''' .. versionadded:: Fluorine Deletes a record set from a DNS zone. This operation cannot be undone. :param name: The name of the record set, relative to the name of the zone. :param zone_name: The name of the DNS zone (without a terminating dot). :param resource_group: The name of the resource group. :param record_type: The type of DNS record in this record set. Record sets of type SOA cannot be deleted (they are deleted when the DNS zone is deleted). Possible values include: 'A', 'AAAA', 'CAA', 'CNAME', 'MX', 'NS', 'PTR', 'SOA', 'SRV', 'TXT' CLI Example: .. code-block:: bash salt-call azurearm_dns.record_set_delete myhost myzone testgroup A ''' result = False dnsconn = __utils__['azurearm.get_client']('dns', **kwargs) try: record_set = dnsconn.record_sets.delete( relative_record_set_name=name, zone_name=zone_name, resource_group_name=resource_group, record_type=record_type, if_match=kwargs.get('if_match') ) result = True except CloudError as exc: __utils__['azurearm.log_cloud_error']('dns', str(exc), **kwargs) return result def record_set_get(name, zone_name, resource_group, record_type, **kwargs): ''' .. versionadded:: Fluorine Get a dictionary representing a record set's properties. :param name: The name of the record set, relative to the name of the zone. :param zone_name: The name of the DNS zone (without a terminating dot). :param resource_group: The name of the resource group. :param record_type: The type of DNS record in this record set. Possible values include: 'A', 'AAAA', 'CAA', 'CNAME', 'MX', 'NS', 'PTR', 'SOA', 'SRV', 'TXT' CLI Example: .. code-block:: bash salt-call azurearm_dns.record_set_get '@' myzone testgroup SOA ''' dnsconn = __utils__['azurearm.get_client']('dns', **kwargs) try: record_set = dnsconn.record_sets.get( relative_record_set_name=name, zone_name=zone_name, resource_group_name=resource_group, record_type=record_type ) result = record_set.as_dict() except CloudError as exc: __utils__['azurearm.log_cloud_error']('dns', str(exc), **kwargs) result = {'error': str(exc)} return result def record_sets_list_by_dns_zone(zone_name, resource_group, top=None, recordsetnamesuffix=None, **kwargs): ''' .. versionadded:: Fluorine Lists all record sets in a DNS zone. :param zone_name: The name of the DNS zone (without a terminating dot). :param resource_group: The name of the resource group. :param top: The maximum number of record sets to return. If not specified, returns up to 100 record sets. :param recordsetnamesuffix: The suffix label of the record set name that has to be used to filter the record set enumerations. CLI Example: .. code-block:: bash salt-call azurearm_dns.record_sets_list_by_dns_zone myzone testgroup ''' result = {} dnsconn = __utils__['azurearm.get_client']('dns', **kwargs) try: record_sets = __utils__['azurearm.paged_object_to_list']( dnsconn.record_sets.list_by_dns_zone( zone_name=zone_name, resource_group_name=resource_group, top=top, recordsetnamesuffix=recordsetnamesuffix ) ) for record_set in record_sets: result[record_set['name']] = record_set except CloudError as exc: __utils__['azurearm.log_cloud_error']('dns', str(exc), **kwargs) result = {'error': str(exc)} return result def zone_create_or_update(name, resource_group, **kwargs): ''' .. versionadded:: Fluorine Creates or updates a DNS zone. Does not modify DNS records within the zone. :param name: The name of the DNS zone to create (without a terminating dot). :param resource_group: The name of the resource group. CLI Example: .. code-block:: bash salt-call azurearm_dns.zone_create_or_update myzone testgroup ''' # DNS zones are global objects kwargs['location'] = 'global' dnsconn = __utils__['azurearm.get_client']('dns', **kwargs) # Convert list of ID strings to list of dictionaries with id key. if isinstance(kwargs.get('registration_virtual_networks'), list): kwargs['registration_virtual_networks'] = [{'id': vnet} for vnet in kwargs['registration_virtual_networks']] if isinstance(kwargs.get('resolution_virtual_networks'), list): kwargs['resolution_virtual_networks'] = [{'id': vnet} for vnet in kwargs['resolution_virtual_networks']] try: zone_model = __utils__['azurearm.create_object_model']('dns', 'Zone', **kwargs) except TypeError as exc: result = {'error': 'The object model could not be built. ({0})'.format(str(exc))} return result try: zone = dnsconn.zones.create_or_update( zone_name=name, resource_group_name=resource_group, parameters=zone_model, if_match=kwargs.get('if_match'), if_none_match=kwargs.get('if_none_match') ) result = zone.as_dict() except CloudError as exc: __utils__['azurearm.log_cloud_error']('dns', str(exc), **kwargs) result = {'error': str(exc)} except SerializationError as exc: result = {'error': 'The object model could not be parsed. ({0})'.format(str(exc))} return result def zone_delete(name, resource_group, **kwargs): ''' .. versionadded:: Fluorine Delete a DNS zone within a resource group. :param name: The name of the DNS zone to delete. :param resource_group: The name of the resource group. CLI Example: .. code-block:: bash salt-call azurearm_dns.zone_delete myzone testgroup ''' result = False dnsconn = __utils__['azurearm.get_client']('dns', **kwargs) try: zone = dnsconn.zones.delete( zone_name=name, resource_group_name=resource_group, if_match=kwargs.get('if_match') ) zone.wait() result = True except CloudError as exc: __utils__['azurearm.log_cloud_error']('dns', str(exc), **kwargs) return result def zone_get(name, resource_group, **kwargs): ''' .. versionadded:: Fluorine Get a dictionary representing a DNS zone's properties, but not the record sets within the zone. :param name: The DNS zone to get. :param resource_group: The name of the resource group. CLI Example: .. code-block:: bash salt-call azurearm_dns.zone_get myzone testgroup ''' dnsconn = __utils__['azurearm.get_client']('dns', **kwargs) try: zone = dnsconn.zones.get( zone_name=name, resource_group_name=resource_group ) result = zone.as_dict() except CloudError as exc: __utils__['azurearm.log_cloud_error']('dns', str(exc), **kwargs) result = {'error': str(exc)} return result def zones_list_by_resource_group(resource_group, top=None, **kwargs): ''' .. versionadded:: Fluorine Lists the DNS zones in a resource group. :param resource_group: The name of the resource group. :param top: The maximum number of DNS zones to return. If not specified, returns up to 100 zones. CLI Example: .. code-block:: bash salt-call azurearm_dns.zones_list_by_resource_group testgroup ''' result = {} dnsconn = __utils__['azurearm.get_client']('dns', **kwargs) try: zones = __utils__['azurearm.paged_object_to_list']( dnsconn.zones.list_by_resource_group( resource_group_name=resource_group, top=top ) ) for zone in zones: result[zone['name']] = zone except CloudError as exc: __utils__['azurearm.log_cloud_error']('dns', str(exc), **kwargs) result = {'error': str(exc)} return result def zones_list(top=None, **kwargs): ''' .. versionadded:: Fluorine Lists the DNS zones in all resource groups in a subscription. :param top: The maximum number of DNS zones to return. If not specified, returns up to 100 zones. CLI Example: .. code-block:: bash salt-call azurearm_dns.zones_list ''' result = {} dnsconn = __utils__['azurearm.get_client']('dns', **kwargs) try: zones = __utils__['azurearm.paged_object_to_list'](dnsconn.zones.list(top=top)) for zone in zones: result[zone['name']] = zone except CloudError as exc: __utils__['azurearm.log_cloud_error']('dns', str(exc), **kwargs) result = {'error': str(exc)} return result
saltstack/salt
salt/modules/azurearm_dns.py
record_sets_list_by_dns_zone
python
def record_sets_list_by_dns_zone(zone_name, resource_group, top=None, recordsetnamesuffix=None, **kwargs): ''' .. versionadded:: Fluorine Lists all record sets in a DNS zone. :param zone_name: The name of the DNS zone (without a terminating dot). :param resource_group: The name of the resource group. :param top: The maximum number of record sets to return. If not specified, returns up to 100 record sets. :param recordsetnamesuffix: The suffix label of the record set name that has to be used to filter the record set enumerations. CLI Example: .. code-block:: bash salt-call azurearm_dns.record_sets_list_by_dns_zone myzone testgroup ''' result = {} dnsconn = __utils__['azurearm.get_client']('dns', **kwargs) try: record_sets = __utils__['azurearm.paged_object_to_list']( dnsconn.record_sets.list_by_dns_zone( zone_name=zone_name, resource_group_name=resource_group, top=top, recordsetnamesuffix=recordsetnamesuffix ) ) for record_set in record_sets: result[record_set['name']] = record_set except CloudError as exc: __utils__['azurearm.log_cloud_error']('dns', str(exc), **kwargs) result = {'error': str(exc)} return result
.. versionadded:: Fluorine Lists all record sets in a DNS zone. :param zone_name: The name of the DNS zone (without a terminating dot). :param resource_group: The name of the resource group. :param top: The maximum number of record sets to return. If not specified, returns up to 100 record sets. :param recordsetnamesuffix: The suffix label of the record set name that has to be used to filter the record set enumerations. CLI Example: .. code-block:: bash salt-call azurearm_dns.record_sets_list_by_dns_zone myzone testgroup
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/azurearm_dns.py#L260-L301
null
# -*- coding: utf-8 -*- ''' Azure (ARM) DNS Execution Module .. versionadded:: Fluorine :maintainer: <nicholasmhughes@gmail.com> :maturity: new :depends: * `azure <https://pypi.python.org/pypi/azure>`_ >= 2.0.0 * `azure-common <https://pypi.python.org/pypi/azure-common>`_ >= 1.1.8 * `azure-mgmt <https://pypi.python.org/pypi/azure-mgmt>`_ >= 1.0.0 * `azure-mgmt-compute <https://pypi.python.org/pypi/azure-mgmt-compute>`_ >= 1.0.0 * `azure-mgmt-dns <https://pypi.python.org/pypi/azure-mgmt-dns>`_ >= 2.0.0rc1 * `azure-mgmt-network <https://pypi.python.org/pypi/azure-mgmt-network>`_ >= 1.7.1 * `azure-mgmt-resource <https://pypi.python.org/pypi/azure-mgmt-resource>`_ >= 1.1.0 * `azure-mgmt-storage <https://pypi.python.org/pypi/azure-mgmt-storage>`_ >= 1.0.0 * `azure-mgmt-web <https://pypi.python.org/pypi/azure-mgmt-web>`_ >= 0.32.0 * `azure-storage <https://pypi.python.org/pypi/azure-storage>`_ >= 0.34.3 * `msrestazure <https://pypi.python.org/pypi/msrestazure>`_ >= 0.4.21 :platform: linux :configuration: This module requires Azure Resource Manager credentials to be passed as keyword arguments to every function in order to work properly. Required provider parameters: if using username and password: * ``subscription_id`` * ``username`` * ``password`` if using a service principal: * ``subscription_id`` * ``tenant`` * ``client_id`` * ``secret`` Optional provider parameters: **cloud_environment**: Used to point the cloud driver to different API endpoints, such as Azure GovCloud. Possible values: * ``AZURE_PUBLIC_CLOUD`` (default) * ``AZURE_CHINA_CLOUD`` * ``AZURE_US_GOV_CLOUD`` * ``AZURE_GERMAN_CLOUD`` ''' # Python libs from __future__ import absolute_import import logging # Azure libs HAS_LIBS = False try: import azure.mgmt.dns.models # pylint: disable=unused-import from msrest.exceptions import SerializationError from msrestazure.azure_exceptions import CloudError HAS_LIBS = True except ImportError: pass __virtualname__ = 'azurearm_dns' log = logging.getLogger(__name__) def __virtual__(): if not HAS_LIBS: return ( False, 'The following dependencies are required to use the AzureARM modules: ' 'Microsoft Azure SDK for Python >= 2.0rc6, ' 'MS REST Azure (msrestazure) >= 0.4' ) return __virtualname__ def record_set_create_or_update(name, zone_name, resource_group, record_type, **kwargs): ''' .. versionadded:: Fluorine Creates or updates a record set within a DNS zone. :param name: The name of the record set, relative to the name of the zone. :param zone_name: The name of the DNS zone (without a terminating dot). :param resource_group: The name of the resource group. :param record_type: The type of DNS record in this record set. Record sets of type SOA can be updated but not created (they are created when the DNS zone is created). Possible values include: 'A', 'AAAA', 'CAA', 'CNAME', 'MX', 'NS', 'PTR', 'SOA', 'SRV', 'TXT' CLI Example: .. code-block:: bash salt-call azurearm_dns.record_set_create_or_update myhost myzone testgroup A arecords='[{ipv4_address: 10.0.0.1}]' ttl=300 ''' dnsconn = __utils__['azurearm.get_client']('dns', **kwargs) try: record_set_model = __utils__['azurearm.create_object_model']('dns', 'RecordSet', **kwargs) except TypeError as exc: result = {'error': 'The object model could not be built. ({0})'.format(str(exc))} return result try: record_set = dnsconn.record_sets.create_or_update( relative_record_set_name=name, zone_name=zone_name, resource_group_name=resource_group, record_type=record_type, parameters=record_set_model, if_match=kwargs.get('if_match'), if_none_match=kwargs.get('if_none_match') ) result = record_set.as_dict() except CloudError as exc: __utils__['azurearm.log_cloud_error']('dns', str(exc), **kwargs) result = {'error': str(exc)} except SerializationError as exc: result = {'error': 'The object model could not be parsed. ({0})'.format(str(exc))} return result def record_set_delete(name, zone_name, resource_group, record_type, **kwargs): ''' .. versionadded:: Fluorine Deletes a record set from a DNS zone. This operation cannot be undone. :param name: The name of the record set, relative to the name of the zone. :param zone_name: The name of the DNS zone (without a terminating dot). :param resource_group: The name of the resource group. :param record_type: The type of DNS record in this record set. Record sets of type SOA cannot be deleted (they are deleted when the DNS zone is deleted). Possible values include: 'A', 'AAAA', 'CAA', 'CNAME', 'MX', 'NS', 'PTR', 'SOA', 'SRV', 'TXT' CLI Example: .. code-block:: bash salt-call azurearm_dns.record_set_delete myhost myzone testgroup A ''' result = False dnsconn = __utils__['azurearm.get_client']('dns', **kwargs) try: record_set = dnsconn.record_sets.delete( relative_record_set_name=name, zone_name=zone_name, resource_group_name=resource_group, record_type=record_type, if_match=kwargs.get('if_match') ) result = True except CloudError as exc: __utils__['azurearm.log_cloud_error']('dns', str(exc), **kwargs) return result def record_set_get(name, zone_name, resource_group, record_type, **kwargs): ''' .. versionadded:: Fluorine Get a dictionary representing a record set's properties. :param name: The name of the record set, relative to the name of the zone. :param zone_name: The name of the DNS zone (without a terminating dot). :param resource_group: The name of the resource group. :param record_type: The type of DNS record in this record set. Possible values include: 'A', 'AAAA', 'CAA', 'CNAME', 'MX', 'NS', 'PTR', 'SOA', 'SRV', 'TXT' CLI Example: .. code-block:: bash salt-call azurearm_dns.record_set_get '@' myzone testgroup SOA ''' dnsconn = __utils__['azurearm.get_client']('dns', **kwargs) try: record_set = dnsconn.record_sets.get( relative_record_set_name=name, zone_name=zone_name, resource_group_name=resource_group, record_type=record_type ) result = record_set.as_dict() except CloudError as exc: __utils__['azurearm.log_cloud_error']('dns', str(exc), **kwargs) result = {'error': str(exc)} return result def record_sets_list_by_type(zone_name, resource_group, record_type, top=None, recordsetnamesuffix=None, **kwargs): ''' .. versionadded:: Fluorine Lists the record sets of a specified type in a DNS zone. :param zone_name: The name of the DNS zone (without a terminating dot). :param resource_group: The name of the resource group. :param record_type: The type of record sets to enumerate. Possible values include: 'A', 'AAAA', 'CAA', 'CNAME', 'MX', 'NS', 'PTR', 'SOA', 'SRV', 'TXT' :param top: The maximum number of record sets to return. If not specified, returns up to 100 record sets. :param recordsetnamesuffix: The suffix label of the record set name that has to be used to filter the record set enumerations. CLI Example: .. code-block:: bash salt-call azurearm_dns.record_sets_list_by_type myzone testgroup SOA ''' result = {} dnsconn = __utils__['azurearm.get_client']('dns', **kwargs) try: record_sets = __utils__['azurearm.paged_object_to_list']( dnsconn.record_sets.list_by_type( zone_name=zone_name, resource_group_name=resource_group, record_type=record_type, top=top, recordsetnamesuffix=recordsetnamesuffix ) ) for record_set in record_sets: result[record_set['name']] = record_set except CloudError as exc: __utils__['azurearm.log_cloud_error']('dns', str(exc), **kwargs) result = {'error': str(exc)} return result def zone_create_or_update(name, resource_group, **kwargs): ''' .. versionadded:: Fluorine Creates or updates a DNS zone. Does not modify DNS records within the zone. :param name: The name of the DNS zone to create (without a terminating dot). :param resource_group: The name of the resource group. CLI Example: .. code-block:: bash salt-call azurearm_dns.zone_create_or_update myzone testgroup ''' # DNS zones are global objects kwargs['location'] = 'global' dnsconn = __utils__['azurearm.get_client']('dns', **kwargs) # Convert list of ID strings to list of dictionaries with id key. if isinstance(kwargs.get('registration_virtual_networks'), list): kwargs['registration_virtual_networks'] = [{'id': vnet} for vnet in kwargs['registration_virtual_networks']] if isinstance(kwargs.get('resolution_virtual_networks'), list): kwargs['resolution_virtual_networks'] = [{'id': vnet} for vnet in kwargs['resolution_virtual_networks']] try: zone_model = __utils__['azurearm.create_object_model']('dns', 'Zone', **kwargs) except TypeError as exc: result = {'error': 'The object model could not be built. ({0})'.format(str(exc))} return result try: zone = dnsconn.zones.create_or_update( zone_name=name, resource_group_name=resource_group, parameters=zone_model, if_match=kwargs.get('if_match'), if_none_match=kwargs.get('if_none_match') ) result = zone.as_dict() except CloudError as exc: __utils__['azurearm.log_cloud_error']('dns', str(exc), **kwargs) result = {'error': str(exc)} except SerializationError as exc: result = {'error': 'The object model could not be parsed. ({0})'.format(str(exc))} return result def zone_delete(name, resource_group, **kwargs): ''' .. versionadded:: Fluorine Delete a DNS zone within a resource group. :param name: The name of the DNS zone to delete. :param resource_group: The name of the resource group. CLI Example: .. code-block:: bash salt-call azurearm_dns.zone_delete myzone testgroup ''' result = False dnsconn = __utils__['azurearm.get_client']('dns', **kwargs) try: zone = dnsconn.zones.delete( zone_name=name, resource_group_name=resource_group, if_match=kwargs.get('if_match') ) zone.wait() result = True except CloudError as exc: __utils__['azurearm.log_cloud_error']('dns', str(exc), **kwargs) return result def zone_get(name, resource_group, **kwargs): ''' .. versionadded:: Fluorine Get a dictionary representing a DNS zone's properties, but not the record sets within the zone. :param name: The DNS zone to get. :param resource_group: The name of the resource group. CLI Example: .. code-block:: bash salt-call azurearm_dns.zone_get myzone testgroup ''' dnsconn = __utils__['azurearm.get_client']('dns', **kwargs) try: zone = dnsconn.zones.get( zone_name=name, resource_group_name=resource_group ) result = zone.as_dict() except CloudError as exc: __utils__['azurearm.log_cloud_error']('dns', str(exc), **kwargs) result = {'error': str(exc)} return result def zones_list_by_resource_group(resource_group, top=None, **kwargs): ''' .. versionadded:: Fluorine Lists the DNS zones in a resource group. :param resource_group: The name of the resource group. :param top: The maximum number of DNS zones to return. If not specified, returns up to 100 zones. CLI Example: .. code-block:: bash salt-call azurearm_dns.zones_list_by_resource_group testgroup ''' result = {} dnsconn = __utils__['azurearm.get_client']('dns', **kwargs) try: zones = __utils__['azurearm.paged_object_to_list']( dnsconn.zones.list_by_resource_group( resource_group_name=resource_group, top=top ) ) for zone in zones: result[zone['name']] = zone except CloudError as exc: __utils__['azurearm.log_cloud_error']('dns', str(exc), **kwargs) result = {'error': str(exc)} return result def zones_list(top=None, **kwargs): ''' .. versionadded:: Fluorine Lists the DNS zones in all resource groups in a subscription. :param top: The maximum number of DNS zones to return. If not specified, returns up to 100 zones. CLI Example: .. code-block:: bash salt-call azurearm_dns.zones_list ''' result = {} dnsconn = __utils__['azurearm.get_client']('dns', **kwargs) try: zones = __utils__['azurearm.paged_object_to_list'](dnsconn.zones.list(top=top)) for zone in zones: result[zone['name']] = zone except CloudError as exc: __utils__['azurearm.log_cloud_error']('dns', str(exc), **kwargs) result = {'error': str(exc)} return result
saltstack/salt
salt/modules/azurearm_dns.py
zone_create_or_update
python
def zone_create_or_update(name, resource_group, **kwargs): ''' .. versionadded:: Fluorine Creates or updates a DNS zone. Does not modify DNS records within the zone. :param name: The name of the DNS zone to create (without a terminating dot). :param resource_group: The name of the resource group. CLI Example: .. code-block:: bash salt-call azurearm_dns.zone_create_or_update myzone testgroup ''' # DNS zones are global objects kwargs['location'] = 'global' dnsconn = __utils__['azurearm.get_client']('dns', **kwargs) # Convert list of ID strings to list of dictionaries with id key. if isinstance(kwargs.get('registration_virtual_networks'), list): kwargs['registration_virtual_networks'] = [{'id': vnet} for vnet in kwargs['registration_virtual_networks']] if isinstance(kwargs.get('resolution_virtual_networks'), list): kwargs['resolution_virtual_networks'] = [{'id': vnet} for vnet in kwargs['resolution_virtual_networks']] try: zone_model = __utils__['azurearm.create_object_model']('dns', 'Zone', **kwargs) except TypeError as exc: result = {'error': 'The object model could not be built. ({0})'.format(str(exc))} return result try: zone = dnsconn.zones.create_or_update( zone_name=name, resource_group_name=resource_group, parameters=zone_model, if_match=kwargs.get('if_match'), if_none_match=kwargs.get('if_none_match') ) result = zone.as_dict() except CloudError as exc: __utils__['azurearm.log_cloud_error']('dns', str(exc), **kwargs) result = {'error': str(exc)} except SerializationError as exc: result = {'error': 'The object model could not be parsed. ({0})'.format(str(exc))} return result
.. versionadded:: Fluorine Creates or updates a DNS zone. Does not modify DNS records within the zone. :param name: The name of the DNS zone to create (without a terminating dot). :param resource_group: The name of the resource group. CLI Example: .. code-block:: bash salt-call azurearm_dns.zone_create_or_update myzone testgroup
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/azurearm_dns.py#L304-L354
null
# -*- coding: utf-8 -*- ''' Azure (ARM) DNS Execution Module .. versionadded:: Fluorine :maintainer: <nicholasmhughes@gmail.com> :maturity: new :depends: * `azure <https://pypi.python.org/pypi/azure>`_ >= 2.0.0 * `azure-common <https://pypi.python.org/pypi/azure-common>`_ >= 1.1.8 * `azure-mgmt <https://pypi.python.org/pypi/azure-mgmt>`_ >= 1.0.0 * `azure-mgmt-compute <https://pypi.python.org/pypi/azure-mgmt-compute>`_ >= 1.0.0 * `azure-mgmt-dns <https://pypi.python.org/pypi/azure-mgmt-dns>`_ >= 2.0.0rc1 * `azure-mgmt-network <https://pypi.python.org/pypi/azure-mgmt-network>`_ >= 1.7.1 * `azure-mgmt-resource <https://pypi.python.org/pypi/azure-mgmt-resource>`_ >= 1.1.0 * `azure-mgmt-storage <https://pypi.python.org/pypi/azure-mgmt-storage>`_ >= 1.0.0 * `azure-mgmt-web <https://pypi.python.org/pypi/azure-mgmt-web>`_ >= 0.32.0 * `azure-storage <https://pypi.python.org/pypi/azure-storage>`_ >= 0.34.3 * `msrestazure <https://pypi.python.org/pypi/msrestazure>`_ >= 0.4.21 :platform: linux :configuration: This module requires Azure Resource Manager credentials to be passed as keyword arguments to every function in order to work properly. Required provider parameters: if using username and password: * ``subscription_id`` * ``username`` * ``password`` if using a service principal: * ``subscription_id`` * ``tenant`` * ``client_id`` * ``secret`` Optional provider parameters: **cloud_environment**: Used to point the cloud driver to different API endpoints, such as Azure GovCloud. Possible values: * ``AZURE_PUBLIC_CLOUD`` (default) * ``AZURE_CHINA_CLOUD`` * ``AZURE_US_GOV_CLOUD`` * ``AZURE_GERMAN_CLOUD`` ''' # Python libs from __future__ import absolute_import import logging # Azure libs HAS_LIBS = False try: import azure.mgmt.dns.models # pylint: disable=unused-import from msrest.exceptions import SerializationError from msrestazure.azure_exceptions import CloudError HAS_LIBS = True except ImportError: pass __virtualname__ = 'azurearm_dns' log = logging.getLogger(__name__) def __virtual__(): if not HAS_LIBS: return ( False, 'The following dependencies are required to use the AzureARM modules: ' 'Microsoft Azure SDK for Python >= 2.0rc6, ' 'MS REST Azure (msrestazure) >= 0.4' ) return __virtualname__ def record_set_create_or_update(name, zone_name, resource_group, record_type, **kwargs): ''' .. versionadded:: Fluorine Creates or updates a record set within a DNS zone. :param name: The name of the record set, relative to the name of the zone. :param zone_name: The name of the DNS zone (without a terminating dot). :param resource_group: The name of the resource group. :param record_type: The type of DNS record in this record set. Record sets of type SOA can be updated but not created (they are created when the DNS zone is created). Possible values include: 'A', 'AAAA', 'CAA', 'CNAME', 'MX', 'NS', 'PTR', 'SOA', 'SRV', 'TXT' CLI Example: .. code-block:: bash salt-call azurearm_dns.record_set_create_or_update myhost myzone testgroup A arecords='[{ipv4_address: 10.0.0.1}]' ttl=300 ''' dnsconn = __utils__['azurearm.get_client']('dns', **kwargs) try: record_set_model = __utils__['azurearm.create_object_model']('dns', 'RecordSet', **kwargs) except TypeError as exc: result = {'error': 'The object model could not be built. ({0})'.format(str(exc))} return result try: record_set = dnsconn.record_sets.create_or_update( relative_record_set_name=name, zone_name=zone_name, resource_group_name=resource_group, record_type=record_type, parameters=record_set_model, if_match=kwargs.get('if_match'), if_none_match=kwargs.get('if_none_match') ) result = record_set.as_dict() except CloudError as exc: __utils__['azurearm.log_cloud_error']('dns', str(exc), **kwargs) result = {'error': str(exc)} except SerializationError as exc: result = {'error': 'The object model could not be parsed. ({0})'.format(str(exc))} return result def record_set_delete(name, zone_name, resource_group, record_type, **kwargs): ''' .. versionadded:: Fluorine Deletes a record set from a DNS zone. This operation cannot be undone. :param name: The name of the record set, relative to the name of the zone. :param zone_name: The name of the DNS zone (without a terminating dot). :param resource_group: The name of the resource group. :param record_type: The type of DNS record in this record set. Record sets of type SOA cannot be deleted (they are deleted when the DNS zone is deleted). Possible values include: 'A', 'AAAA', 'CAA', 'CNAME', 'MX', 'NS', 'PTR', 'SOA', 'SRV', 'TXT' CLI Example: .. code-block:: bash salt-call azurearm_dns.record_set_delete myhost myzone testgroup A ''' result = False dnsconn = __utils__['azurearm.get_client']('dns', **kwargs) try: record_set = dnsconn.record_sets.delete( relative_record_set_name=name, zone_name=zone_name, resource_group_name=resource_group, record_type=record_type, if_match=kwargs.get('if_match') ) result = True except CloudError as exc: __utils__['azurearm.log_cloud_error']('dns', str(exc), **kwargs) return result def record_set_get(name, zone_name, resource_group, record_type, **kwargs): ''' .. versionadded:: Fluorine Get a dictionary representing a record set's properties. :param name: The name of the record set, relative to the name of the zone. :param zone_name: The name of the DNS zone (without a terminating dot). :param resource_group: The name of the resource group. :param record_type: The type of DNS record in this record set. Possible values include: 'A', 'AAAA', 'CAA', 'CNAME', 'MX', 'NS', 'PTR', 'SOA', 'SRV', 'TXT' CLI Example: .. code-block:: bash salt-call azurearm_dns.record_set_get '@' myzone testgroup SOA ''' dnsconn = __utils__['azurearm.get_client']('dns', **kwargs) try: record_set = dnsconn.record_sets.get( relative_record_set_name=name, zone_name=zone_name, resource_group_name=resource_group, record_type=record_type ) result = record_set.as_dict() except CloudError as exc: __utils__['azurearm.log_cloud_error']('dns', str(exc), **kwargs) result = {'error': str(exc)} return result def record_sets_list_by_type(zone_name, resource_group, record_type, top=None, recordsetnamesuffix=None, **kwargs): ''' .. versionadded:: Fluorine Lists the record sets of a specified type in a DNS zone. :param zone_name: The name of the DNS zone (without a terminating dot). :param resource_group: The name of the resource group. :param record_type: The type of record sets to enumerate. Possible values include: 'A', 'AAAA', 'CAA', 'CNAME', 'MX', 'NS', 'PTR', 'SOA', 'SRV', 'TXT' :param top: The maximum number of record sets to return. If not specified, returns up to 100 record sets. :param recordsetnamesuffix: The suffix label of the record set name that has to be used to filter the record set enumerations. CLI Example: .. code-block:: bash salt-call azurearm_dns.record_sets_list_by_type myzone testgroup SOA ''' result = {} dnsconn = __utils__['azurearm.get_client']('dns', **kwargs) try: record_sets = __utils__['azurearm.paged_object_to_list']( dnsconn.record_sets.list_by_type( zone_name=zone_name, resource_group_name=resource_group, record_type=record_type, top=top, recordsetnamesuffix=recordsetnamesuffix ) ) for record_set in record_sets: result[record_set['name']] = record_set except CloudError as exc: __utils__['azurearm.log_cloud_error']('dns', str(exc), **kwargs) result = {'error': str(exc)} return result def record_sets_list_by_dns_zone(zone_name, resource_group, top=None, recordsetnamesuffix=None, **kwargs): ''' .. versionadded:: Fluorine Lists all record sets in a DNS zone. :param zone_name: The name of the DNS zone (without a terminating dot). :param resource_group: The name of the resource group. :param top: The maximum number of record sets to return. If not specified, returns up to 100 record sets. :param recordsetnamesuffix: The suffix label of the record set name that has to be used to filter the record set enumerations. CLI Example: .. code-block:: bash salt-call azurearm_dns.record_sets_list_by_dns_zone myzone testgroup ''' result = {} dnsconn = __utils__['azurearm.get_client']('dns', **kwargs) try: record_sets = __utils__['azurearm.paged_object_to_list']( dnsconn.record_sets.list_by_dns_zone( zone_name=zone_name, resource_group_name=resource_group, top=top, recordsetnamesuffix=recordsetnamesuffix ) ) for record_set in record_sets: result[record_set['name']] = record_set except CloudError as exc: __utils__['azurearm.log_cloud_error']('dns', str(exc), **kwargs) result = {'error': str(exc)} return result def zone_delete(name, resource_group, **kwargs): ''' .. versionadded:: Fluorine Delete a DNS zone within a resource group. :param name: The name of the DNS zone to delete. :param resource_group: The name of the resource group. CLI Example: .. code-block:: bash salt-call azurearm_dns.zone_delete myzone testgroup ''' result = False dnsconn = __utils__['azurearm.get_client']('dns', **kwargs) try: zone = dnsconn.zones.delete( zone_name=name, resource_group_name=resource_group, if_match=kwargs.get('if_match') ) zone.wait() result = True except CloudError as exc: __utils__['azurearm.log_cloud_error']('dns', str(exc), **kwargs) return result def zone_get(name, resource_group, **kwargs): ''' .. versionadded:: Fluorine Get a dictionary representing a DNS zone's properties, but not the record sets within the zone. :param name: The DNS zone to get. :param resource_group: The name of the resource group. CLI Example: .. code-block:: bash salt-call azurearm_dns.zone_get myzone testgroup ''' dnsconn = __utils__['azurearm.get_client']('dns', **kwargs) try: zone = dnsconn.zones.get( zone_name=name, resource_group_name=resource_group ) result = zone.as_dict() except CloudError as exc: __utils__['azurearm.log_cloud_error']('dns', str(exc), **kwargs) result = {'error': str(exc)} return result def zones_list_by_resource_group(resource_group, top=None, **kwargs): ''' .. versionadded:: Fluorine Lists the DNS zones in a resource group. :param resource_group: The name of the resource group. :param top: The maximum number of DNS zones to return. If not specified, returns up to 100 zones. CLI Example: .. code-block:: bash salt-call azurearm_dns.zones_list_by_resource_group testgroup ''' result = {} dnsconn = __utils__['azurearm.get_client']('dns', **kwargs) try: zones = __utils__['azurearm.paged_object_to_list']( dnsconn.zones.list_by_resource_group( resource_group_name=resource_group, top=top ) ) for zone in zones: result[zone['name']] = zone except CloudError as exc: __utils__['azurearm.log_cloud_error']('dns', str(exc), **kwargs) result = {'error': str(exc)} return result def zones_list(top=None, **kwargs): ''' .. versionadded:: Fluorine Lists the DNS zones in all resource groups in a subscription. :param top: The maximum number of DNS zones to return. If not specified, returns up to 100 zones. CLI Example: .. code-block:: bash salt-call azurearm_dns.zones_list ''' result = {} dnsconn = __utils__['azurearm.get_client']('dns', **kwargs) try: zones = __utils__['azurearm.paged_object_to_list'](dnsconn.zones.list(top=top)) for zone in zones: result[zone['name']] = zone except CloudError as exc: __utils__['azurearm.log_cloud_error']('dns', str(exc), **kwargs) result = {'error': str(exc)} return result
saltstack/salt
salt/modules/azurearm_dns.py
zone_delete
python
def zone_delete(name, resource_group, **kwargs): ''' .. versionadded:: Fluorine Delete a DNS zone within a resource group. :param name: The name of the DNS zone to delete. :param resource_group: The name of the resource group. CLI Example: .. code-block:: bash salt-call azurearm_dns.zone_delete myzone testgroup ''' result = False dnsconn = __utils__['azurearm.get_client']('dns', **kwargs) try: zone = dnsconn.zones.delete( zone_name=name, resource_group_name=resource_group, if_match=kwargs.get('if_match') ) zone.wait() result = True except CloudError as exc: __utils__['azurearm.log_cloud_error']('dns', str(exc), **kwargs) return result
.. versionadded:: Fluorine Delete a DNS zone within a resource group. :param name: The name of the DNS zone to delete. :param resource_group: The name of the resource group. CLI Example: .. code-block:: bash salt-call azurearm_dns.zone_delete myzone testgroup
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/azurearm_dns.py#L357-L387
null
# -*- coding: utf-8 -*- ''' Azure (ARM) DNS Execution Module .. versionadded:: Fluorine :maintainer: <nicholasmhughes@gmail.com> :maturity: new :depends: * `azure <https://pypi.python.org/pypi/azure>`_ >= 2.0.0 * `azure-common <https://pypi.python.org/pypi/azure-common>`_ >= 1.1.8 * `azure-mgmt <https://pypi.python.org/pypi/azure-mgmt>`_ >= 1.0.0 * `azure-mgmt-compute <https://pypi.python.org/pypi/azure-mgmt-compute>`_ >= 1.0.0 * `azure-mgmt-dns <https://pypi.python.org/pypi/azure-mgmt-dns>`_ >= 2.0.0rc1 * `azure-mgmt-network <https://pypi.python.org/pypi/azure-mgmt-network>`_ >= 1.7.1 * `azure-mgmt-resource <https://pypi.python.org/pypi/azure-mgmt-resource>`_ >= 1.1.0 * `azure-mgmt-storage <https://pypi.python.org/pypi/azure-mgmt-storage>`_ >= 1.0.0 * `azure-mgmt-web <https://pypi.python.org/pypi/azure-mgmt-web>`_ >= 0.32.0 * `azure-storage <https://pypi.python.org/pypi/azure-storage>`_ >= 0.34.3 * `msrestazure <https://pypi.python.org/pypi/msrestazure>`_ >= 0.4.21 :platform: linux :configuration: This module requires Azure Resource Manager credentials to be passed as keyword arguments to every function in order to work properly. Required provider parameters: if using username and password: * ``subscription_id`` * ``username`` * ``password`` if using a service principal: * ``subscription_id`` * ``tenant`` * ``client_id`` * ``secret`` Optional provider parameters: **cloud_environment**: Used to point the cloud driver to different API endpoints, such as Azure GovCloud. Possible values: * ``AZURE_PUBLIC_CLOUD`` (default) * ``AZURE_CHINA_CLOUD`` * ``AZURE_US_GOV_CLOUD`` * ``AZURE_GERMAN_CLOUD`` ''' # Python libs from __future__ import absolute_import import logging # Azure libs HAS_LIBS = False try: import azure.mgmt.dns.models # pylint: disable=unused-import from msrest.exceptions import SerializationError from msrestazure.azure_exceptions import CloudError HAS_LIBS = True except ImportError: pass __virtualname__ = 'azurearm_dns' log = logging.getLogger(__name__) def __virtual__(): if not HAS_LIBS: return ( False, 'The following dependencies are required to use the AzureARM modules: ' 'Microsoft Azure SDK for Python >= 2.0rc6, ' 'MS REST Azure (msrestazure) >= 0.4' ) return __virtualname__ def record_set_create_or_update(name, zone_name, resource_group, record_type, **kwargs): ''' .. versionadded:: Fluorine Creates or updates a record set within a DNS zone. :param name: The name of the record set, relative to the name of the zone. :param zone_name: The name of the DNS zone (without a terminating dot). :param resource_group: The name of the resource group. :param record_type: The type of DNS record in this record set. Record sets of type SOA can be updated but not created (they are created when the DNS zone is created). Possible values include: 'A', 'AAAA', 'CAA', 'CNAME', 'MX', 'NS', 'PTR', 'SOA', 'SRV', 'TXT' CLI Example: .. code-block:: bash salt-call azurearm_dns.record_set_create_or_update myhost myzone testgroup A arecords='[{ipv4_address: 10.0.0.1}]' ttl=300 ''' dnsconn = __utils__['azurearm.get_client']('dns', **kwargs) try: record_set_model = __utils__['azurearm.create_object_model']('dns', 'RecordSet', **kwargs) except TypeError as exc: result = {'error': 'The object model could not be built. ({0})'.format(str(exc))} return result try: record_set = dnsconn.record_sets.create_or_update( relative_record_set_name=name, zone_name=zone_name, resource_group_name=resource_group, record_type=record_type, parameters=record_set_model, if_match=kwargs.get('if_match'), if_none_match=kwargs.get('if_none_match') ) result = record_set.as_dict() except CloudError as exc: __utils__['azurearm.log_cloud_error']('dns', str(exc), **kwargs) result = {'error': str(exc)} except SerializationError as exc: result = {'error': 'The object model could not be parsed. ({0})'.format(str(exc))} return result def record_set_delete(name, zone_name, resource_group, record_type, **kwargs): ''' .. versionadded:: Fluorine Deletes a record set from a DNS zone. This operation cannot be undone. :param name: The name of the record set, relative to the name of the zone. :param zone_name: The name of the DNS zone (without a terminating dot). :param resource_group: The name of the resource group. :param record_type: The type of DNS record in this record set. Record sets of type SOA cannot be deleted (they are deleted when the DNS zone is deleted). Possible values include: 'A', 'AAAA', 'CAA', 'CNAME', 'MX', 'NS', 'PTR', 'SOA', 'SRV', 'TXT' CLI Example: .. code-block:: bash salt-call azurearm_dns.record_set_delete myhost myzone testgroup A ''' result = False dnsconn = __utils__['azurearm.get_client']('dns', **kwargs) try: record_set = dnsconn.record_sets.delete( relative_record_set_name=name, zone_name=zone_name, resource_group_name=resource_group, record_type=record_type, if_match=kwargs.get('if_match') ) result = True except CloudError as exc: __utils__['azurearm.log_cloud_error']('dns', str(exc), **kwargs) return result def record_set_get(name, zone_name, resource_group, record_type, **kwargs): ''' .. versionadded:: Fluorine Get a dictionary representing a record set's properties. :param name: The name of the record set, relative to the name of the zone. :param zone_name: The name of the DNS zone (without a terminating dot). :param resource_group: The name of the resource group. :param record_type: The type of DNS record in this record set. Possible values include: 'A', 'AAAA', 'CAA', 'CNAME', 'MX', 'NS', 'PTR', 'SOA', 'SRV', 'TXT' CLI Example: .. code-block:: bash salt-call azurearm_dns.record_set_get '@' myzone testgroup SOA ''' dnsconn = __utils__['azurearm.get_client']('dns', **kwargs) try: record_set = dnsconn.record_sets.get( relative_record_set_name=name, zone_name=zone_name, resource_group_name=resource_group, record_type=record_type ) result = record_set.as_dict() except CloudError as exc: __utils__['azurearm.log_cloud_error']('dns', str(exc), **kwargs) result = {'error': str(exc)} return result def record_sets_list_by_type(zone_name, resource_group, record_type, top=None, recordsetnamesuffix=None, **kwargs): ''' .. versionadded:: Fluorine Lists the record sets of a specified type in a DNS zone. :param zone_name: The name of the DNS zone (without a terminating dot). :param resource_group: The name of the resource group. :param record_type: The type of record sets to enumerate. Possible values include: 'A', 'AAAA', 'CAA', 'CNAME', 'MX', 'NS', 'PTR', 'SOA', 'SRV', 'TXT' :param top: The maximum number of record sets to return. If not specified, returns up to 100 record sets. :param recordsetnamesuffix: The suffix label of the record set name that has to be used to filter the record set enumerations. CLI Example: .. code-block:: bash salt-call azurearm_dns.record_sets_list_by_type myzone testgroup SOA ''' result = {} dnsconn = __utils__['azurearm.get_client']('dns', **kwargs) try: record_sets = __utils__['azurearm.paged_object_to_list']( dnsconn.record_sets.list_by_type( zone_name=zone_name, resource_group_name=resource_group, record_type=record_type, top=top, recordsetnamesuffix=recordsetnamesuffix ) ) for record_set in record_sets: result[record_set['name']] = record_set except CloudError as exc: __utils__['azurearm.log_cloud_error']('dns', str(exc), **kwargs) result = {'error': str(exc)} return result def record_sets_list_by_dns_zone(zone_name, resource_group, top=None, recordsetnamesuffix=None, **kwargs): ''' .. versionadded:: Fluorine Lists all record sets in a DNS zone. :param zone_name: The name of the DNS zone (without a terminating dot). :param resource_group: The name of the resource group. :param top: The maximum number of record sets to return. If not specified, returns up to 100 record sets. :param recordsetnamesuffix: The suffix label of the record set name that has to be used to filter the record set enumerations. CLI Example: .. code-block:: bash salt-call azurearm_dns.record_sets_list_by_dns_zone myzone testgroup ''' result = {} dnsconn = __utils__['azurearm.get_client']('dns', **kwargs) try: record_sets = __utils__['azurearm.paged_object_to_list']( dnsconn.record_sets.list_by_dns_zone( zone_name=zone_name, resource_group_name=resource_group, top=top, recordsetnamesuffix=recordsetnamesuffix ) ) for record_set in record_sets: result[record_set['name']] = record_set except CloudError as exc: __utils__['azurearm.log_cloud_error']('dns', str(exc), **kwargs) result = {'error': str(exc)} return result def zone_create_or_update(name, resource_group, **kwargs): ''' .. versionadded:: Fluorine Creates or updates a DNS zone. Does not modify DNS records within the zone. :param name: The name of the DNS zone to create (without a terminating dot). :param resource_group: The name of the resource group. CLI Example: .. code-block:: bash salt-call azurearm_dns.zone_create_or_update myzone testgroup ''' # DNS zones are global objects kwargs['location'] = 'global' dnsconn = __utils__['azurearm.get_client']('dns', **kwargs) # Convert list of ID strings to list of dictionaries with id key. if isinstance(kwargs.get('registration_virtual_networks'), list): kwargs['registration_virtual_networks'] = [{'id': vnet} for vnet in kwargs['registration_virtual_networks']] if isinstance(kwargs.get('resolution_virtual_networks'), list): kwargs['resolution_virtual_networks'] = [{'id': vnet} for vnet in kwargs['resolution_virtual_networks']] try: zone_model = __utils__['azurearm.create_object_model']('dns', 'Zone', **kwargs) except TypeError as exc: result = {'error': 'The object model could not be built. ({0})'.format(str(exc))} return result try: zone = dnsconn.zones.create_or_update( zone_name=name, resource_group_name=resource_group, parameters=zone_model, if_match=kwargs.get('if_match'), if_none_match=kwargs.get('if_none_match') ) result = zone.as_dict() except CloudError as exc: __utils__['azurearm.log_cloud_error']('dns', str(exc), **kwargs) result = {'error': str(exc)} except SerializationError as exc: result = {'error': 'The object model could not be parsed. ({0})'.format(str(exc))} return result def zone_get(name, resource_group, **kwargs): ''' .. versionadded:: Fluorine Get a dictionary representing a DNS zone's properties, but not the record sets within the zone. :param name: The DNS zone to get. :param resource_group: The name of the resource group. CLI Example: .. code-block:: bash salt-call azurearm_dns.zone_get myzone testgroup ''' dnsconn = __utils__['azurearm.get_client']('dns', **kwargs) try: zone = dnsconn.zones.get( zone_name=name, resource_group_name=resource_group ) result = zone.as_dict() except CloudError as exc: __utils__['azurearm.log_cloud_error']('dns', str(exc), **kwargs) result = {'error': str(exc)} return result def zones_list_by_resource_group(resource_group, top=None, **kwargs): ''' .. versionadded:: Fluorine Lists the DNS zones in a resource group. :param resource_group: The name of the resource group. :param top: The maximum number of DNS zones to return. If not specified, returns up to 100 zones. CLI Example: .. code-block:: bash salt-call azurearm_dns.zones_list_by_resource_group testgroup ''' result = {} dnsconn = __utils__['azurearm.get_client']('dns', **kwargs) try: zones = __utils__['azurearm.paged_object_to_list']( dnsconn.zones.list_by_resource_group( resource_group_name=resource_group, top=top ) ) for zone in zones: result[zone['name']] = zone except CloudError as exc: __utils__['azurearm.log_cloud_error']('dns', str(exc), **kwargs) result = {'error': str(exc)} return result def zones_list(top=None, **kwargs): ''' .. versionadded:: Fluorine Lists the DNS zones in all resource groups in a subscription. :param top: The maximum number of DNS zones to return. If not specified, returns up to 100 zones. CLI Example: .. code-block:: bash salt-call azurearm_dns.zones_list ''' result = {} dnsconn = __utils__['azurearm.get_client']('dns', **kwargs) try: zones = __utils__['azurearm.paged_object_to_list'](dnsconn.zones.list(top=top)) for zone in zones: result[zone['name']] = zone except CloudError as exc: __utils__['azurearm.log_cloud_error']('dns', str(exc), **kwargs) result = {'error': str(exc)} return result
saltstack/salt
salt/modules/azurearm_dns.py
zone_get
python
def zone_get(name, resource_group, **kwargs): ''' .. versionadded:: Fluorine Get a dictionary representing a DNS zone's properties, but not the record sets within the zone. :param name: The DNS zone to get. :param resource_group: The name of the resource group. CLI Example: .. code-block:: bash salt-call azurearm_dns.zone_get myzone testgroup ''' dnsconn = __utils__['azurearm.get_client']('dns', **kwargs) try: zone = dnsconn.zones.get( zone_name=name, resource_group_name=resource_group ) result = zone.as_dict() except CloudError as exc: __utils__['azurearm.log_cloud_error']('dns', str(exc), **kwargs) result = {'error': str(exc)} return result
.. versionadded:: Fluorine Get a dictionary representing a DNS zone's properties, but not the record sets within the zone. :param name: The DNS zone to get. :param resource_group: The name of the resource group. CLI Example: .. code-block:: bash salt-call azurearm_dns.zone_get myzone testgroup
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/azurearm_dns.py#L390-L420
null
# -*- coding: utf-8 -*- ''' Azure (ARM) DNS Execution Module .. versionadded:: Fluorine :maintainer: <nicholasmhughes@gmail.com> :maturity: new :depends: * `azure <https://pypi.python.org/pypi/azure>`_ >= 2.0.0 * `azure-common <https://pypi.python.org/pypi/azure-common>`_ >= 1.1.8 * `azure-mgmt <https://pypi.python.org/pypi/azure-mgmt>`_ >= 1.0.0 * `azure-mgmt-compute <https://pypi.python.org/pypi/azure-mgmt-compute>`_ >= 1.0.0 * `azure-mgmt-dns <https://pypi.python.org/pypi/azure-mgmt-dns>`_ >= 2.0.0rc1 * `azure-mgmt-network <https://pypi.python.org/pypi/azure-mgmt-network>`_ >= 1.7.1 * `azure-mgmt-resource <https://pypi.python.org/pypi/azure-mgmt-resource>`_ >= 1.1.0 * `azure-mgmt-storage <https://pypi.python.org/pypi/azure-mgmt-storage>`_ >= 1.0.0 * `azure-mgmt-web <https://pypi.python.org/pypi/azure-mgmt-web>`_ >= 0.32.0 * `azure-storage <https://pypi.python.org/pypi/azure-storage>`_ >= 0.34.3 * `msrestazure <https://pypi.python.org/pypi/msrestazure>`_ >= 0.4.21 :platform: linux :configuration: This module requires Azure Resource Manager credentials to be passed as keyword arguments to every function in order to work properly. Required provider parameters: if using username and password: * ``subscription_id`` * ``username`` * ``password`` if using a service principal: * ``subscription_id`` * ``tenant`` * ``client_id`` * ``secret`` Optional provider parameters: **cloud_environment**: Used to point the cloud driver to different API endpoints, such as Azure GovCloud. Possible values: * ``AZURE_PUBLIC_CLOUD`` (default) * ``AZURE_CHINA_CLOUD`` * ``AZURE_US_GOV_CLOUD`` * ``AZURE_GERMAN_CLOUD`` ''' # Python libs from __future__ import absolute_import import logging # Azure libs HAS_LIBS = False try: import azure.mgmt.dns.models # pylint: disable=unused-import from msrest.exceptions import SerializationError from msrestazure.azure_exceptions import CloudError HAS_LIBS = True except ImportError: pass __virtualname__ = 'azurearm_dns' log = logging.getLogger(__name__) def __virtual__(): if not HAS_LIBS: return ( False, 'The following dependencies are required to use the AzureARM modules: ' 'Microsoft Azure SDK for Python >= 2.0rc6, ' 'MS REST Azure (msrestazure) >= 0.4' ) return __virtualname__ def record_set_create_or_update(name, zone_name, resource_group, record_type, **kwargs): ''' .. versionadded:: Fluorine Creates or updates a record set within a DNS zone. :param name: The name of the record set, relative to the name of the zone. :param zone_name: The name of the DNS zone (without a terminating dot). :param resource_group: The name of the resource group. :param record_type: The type of DNS record in this record set. Record sets of type SOA can be updated but not created (they are created when the DNS zone is created). Possible values include: 'A', 'AAAA', 'CAA', 'CNAME', 'MX', 'NS', 'PTR', 'SOA', 'SRV', 'TXT' CLI Example: .. code-block:: bash salt-call azurearm_dns.record_set_create_or_update myhost myzone testgroup A arecords='[{ipv4_address: 10.0.0.1}]' ttl=300 ''' dnsconn = __utils__['azurearm.get_client']('dns', **kwargs) try: record_set_model = __utils__['azurearm.create_object_model']('dns', 'RecordSet', **kwargs) except TypeError as exc: result = {'error': 'The object model could not be built. ({0})'.format(str(exc))} return result try: record_set = dnsconn.record_sets.create_or_update( relative_record_set_name=name, zone_name=zone_name, resource_group_name=resource_group, record_type=record_type, parameters=record_set_model, if_match=kwargs.get('if_match'), if_none_match=kwargs.get('if_none_match') ) result = record_set.as_dict() except CloudError as exc: __utils__['azurearm.log_cloud_error']('dns', str(exc), **kwargs) result = {'error': str(exc)} except SerializationError as exc: result = {'error': 'The object model could not be parsed. ({0})'.format(str(exc))} return result def record_set_delete(name, zone_name, resource_group, record_type, **kwargs): ''' .. versionadded:: Fluorine Deletes a record set from a DNS zone. This operation cannot be undone. :param name: The name of the record set, relative to the name of the zone. :param zone_name: The name of the DNS zone (without a terminating dot). :param resource_group: The name of the resource group. :param record_type: The type of DNS record in this record set. Record sets of type SOA cannot be deleted (they are deleted when the DNS zone is deleted). Possible values include: 'A', 'AAAA', 'CAA', 'CNAME', 'MX', 'NS', 'PTR', 'SOA', 'SRV', 'TXT' CLI Example: .. code-block:: bash salt-call azurearm_dns.record_set_delete myhost myzone testgroup A ''' result = False dnsconn = __utils__['azurearm.get_client']('dns', **kwargs) try: record_set = dnsconn.record_sets.delete( relative_record_set_name=name, zone_name=zone_name, resource_group_name=resource_group, record_type=record_type, if_match=kwargs.get('if_match') ) result = True except CloudError as exc: __utils__['azurearm.log_cloud_error']('dns', str(exc), **kwargs) return result def record_set_get(name, zone_name, resource_group, record_type, **kwargs): ''' .. versionadded:: Fluorine Get a dictionary representing a record set's properties. :param name: The name of the record set, relative to the name of the zone. :param zone_name: The name of the DNS zone (without a terminating dot). :param resource_group: The name of the resource group. :param record_type: The type of DNS record in this record set. Possible values include: 'A', 'AAAA', 'CAA', 'CNAME', 'MX', 'NS', 'PTR', 'SOA', 'SRV', 'TXT' CLI Example: .. code-block:: bash salt-call azurearm_dns.record_set_get '@' myzone testgroup SOA ''' dnsconn = __utils__['azurearm.get_client']('dns', **kwargs) try: record_set = dnsconn.record_sets.get( relative_record_set_name=name, zone_name=zone_name, resource_group_name=resource_group, record_type=record_type ) result = record_set.as_dict() except CloudError as exc: __utils__['azurearm.log_cloud_error']('dns', str(exc), **kwargs) result = {'error': str(exc)} return result def record_sets_list_by_type(zone_name, resource_group, record_type, top=None, recordsetnamesuffix=None, **kwargs): ''' .. versionadded:: Fluorine Lists the record sets of a specified type in a DNS zone. :param zone_name: The name of the DNS zone (without a terminating dot). :param resource_group: The name of the resource group. :param record_type: The type of record sets to enumerate. Possible values include: 'A', 'AAAA', 'CAA', 'CNAME', 'MX', 'NS', 'PTR', 'SOA', 'SRV', 'TXT' :param top: The maximum number of record sets to return. If not specified, returns up to 100 record sets. :param recordsetnamesuffix: The suffix label of the record set name that has to be used to filter the record set enumerations. CLI Example: .. code-block:: bash salt-call azurearm_dns.record_sets_list_by_type myzone testgroup SOA ''' result = {} dnsconn = __utils__['azurearm.get_client']('dns', **kwargs) try: record_sets = __utils__['azurearm.paged_object_to_list']( dnsconn.record_sets.list_by_type( zone_name=zone_name, resource_group_name=resource_group, record_type=record_type, top=top, recordsetnamesuffix=recordsetnamesuffix ) ) for record_set in record_sets: result[record_set['name']] = record_set except CloudError as exc: __utils__['azurearm.log_cloud_error']('dns', str(exc), **kwargs) result = {'error': str(exc)} return result def record_sets_list_by_dns_zone(zone_name, resource_group, top=None, recordsetnamesuffix=None, **kwargs): ''' .. versionadded:: Fluorine Lists all record sets in a DNS zone. :param zone_name: The name of the DNS zone (without a terminating dot). :param resource_group: The name of the resource group. :param top: The maximum number of record sets to return. If not specified, returns up to 100 record sets. :param recordsetnamesuffix: The suffix label of the record set name that has to be used to filter the record set enumerations. CLI Example: .. code-block:: bash salt-call azurearm_dns.record_sets_list_by_dns_zone myzone testgroup ''' result = {} dnsconn = __utils__['azurearm.get_client']('dns', **kwargs) try: record_sets = __utils__['azurearm.paged_object_to_list']( dnsconn.record_sets.list_by_dns_zone( zone_name=zone_name, resource_group_name=resource_group, top=top, recordsetnamesuffix=recordsetnamesuffix ) ) for record_set in record_sets: result[record_set['name']] = record_set except CloudError as exc: __utils__['azurearm.log_cloud_error']('dns', str(exc), **kwargs) result = {'error': str(exc)} return result def zone_create_or_update(name, resource_group, **kwargs): ''' .. versionadded:: Fluorine Creates or updates a DNS zone. Does not modify DNS records within the zone. :param name: The name of the DNS zone to create (without a terminating dot). :param resource_group: The name of the resource group. CLI Example: .. code-block:: bash salt-call azurearm_dns.zone_create_or_update myzone testgroup ''' # DNS zones are global objects kwargs['location'] = 'global' dnsconn = __utils__['azurearm.get_client']('dns', **kwargs) # Convert list of ID strings to list of dictionaries with id key. if isinstance(kwargs.get('registration_virtual_networks'), list): kwargs['registration_virtual_networks'] = [{'id': vnet} for vnet in kwargs['registration_virtual_networks']] if isinstance(kwargs.get('resolution_virtual_networks'), list): kwargs['resolution_virtual_networks'] = [{'id': vnet} for vnet in kwargs['resolution_virtual_networks']] try: zone_model = __utils__['azurearm.create_object_model']('dns', 'Zone', **kwargs) except TypeError as exc: result = {'error': 'The object model could not be built. ({0})'.format(str(exc))} return result try: zone = dnsconn.zones.create_or_update( zone_name=name, resource_group_name=resource_group, parameters=zone_model, if_match=kwargs.get('if_match'), if_none_match=kwargs.get('if_none_match') ) result = zone.as_dict() except CloudError as exc: __utils__['azurearm.log_cloud_error']('dns', str(exc), **kwargs) result = {'error': str(exc)} except SerializationError as exc: result = {'error': 'The object model could not be parsed. ({0})'.format(str(exc))} return result def zone_delete(name, resource_group, **kwargs): ''' .. versionadded:: Fluorine Delete a DNS zone within a resource group. :param name: The name of the DNS zone to delete. :param resource_group: The name of the resource group. CLI Example: .. code-block:: bash salt-call azurearm_dns.zone_delete myzone testgroup ''' result = False dnsconn = __utils__['azurearm.get_client']('dns', **kwargs) try: zone = dnsconn.zones.delete( zone_name=name, resource_group_name=resource_group, if_match=kwargs.get('if_match') ) zone.wait() result = True except CloudError as exc: __utils__['azurearm.log_cloud_error']('dns', str(exc), **kwargs) return result def zones_list_by_resource_group(resource_group, top=None, **kwargs): ''' .. versionadded:: Fluorine Lists the DNS zones in a resource group. :param resource_group: The name of the resource group. :param top: The maximum number of DNS zones to return. If not specified, returns up to 100 zones. CLI Example: .. code-block:: bash salt-call azurearm_dns.zones_list_by_resource_group testgroup ''' result = {} dnsconn = __utils__['azurearm.get_client']('dns', **kwargs) try: zones = __utils__['azurearm.paged_object_to_list']( dnsconn.zones.list_by_resource_group( resource_group_name=resource_group, top=top ) ) for zone in zones: result[zone['name']] = zone except CloudError as exc: __utils__['azurearm.log_cloud_error']('dns', str(exc), **kwargs) result = {'error': str(exc)} return result def zones_list(top=None, **kwargs): ''' .. versionadded:: Fluorine Lists the DNS zones in all resource groups in a subscription. :param top: The maximum number of DNS zones to return. If not specified, returns up to 100 zones. CLI Example: .. code-block:: bash salt-call azurearm_dns.zones_list ''' result = {} dnsconn = __utils__['azurearm.get_client']('dns', **kwargs) try: zones = __utils__['azurearm.paged_object_to_list'](dnsconn.zones.list(top=top)) for zone in zones: result[zone['name']] = zone except CloudError as exc: __utils__['azurearm.log_cloud_error']('dns', str(exc), **kwargs) result = {'error': str(exc)} return result
saltstack/salt
salt/modules/azurearm_dns.py
zones_list_by_resource_group
python
def zones_list_by_resource_group(resource_group, top=None, **kwargs): ''' .. versionadded:: Fluorine Lists the DNS zones in a resource group. :param resource_group: The name of the resource group. :param top: The maximum number of DNS zones to return. If not specified, returns up to 100 zones. CLI Example: .. code-block:: bash salt-call azurearm_dns.zones_list_by_resource_group testgroup ''' result = {} dnsconn = __utils__['azurearm.get_client']('dns', **kwargs) try: zones = __utils__['azurearm.paged_object_to_list']( dnsconn.zones.list_by_resource_group( resource_group_name=resource_group, top=top ) ) for zone in zones: result[zone['name']] = zone except CloudError as exc: __utils__['azurearm.log_cloud_error']('dns', str(exc), **kwargs) result = {'error': str(exc)} return result
.. versionadded:: Fluorine Lists the DNS zones in a resource group. :param resource_group: The name of the resource group. :param top: The maximum number of DNS zones to return. If not specified, returns up to 100 zones. CLI Example: .. code-block:: bash salt-call azurearm_dns.zones_list_by_resource_group testgroup
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/azurearm_dns.py#L423-L457
null
# -*- coding: utf-8 -*- ''' Azure (ARM) DNS Execution Module .. versionadded:: Fluorine :maintainer: <nicholasmhughes@gmail.com> :maturity: new :depends: * `azure <https://pypi.python.org/pypi/azure>`_ >= 2.0.0 * `azure-common <https://pypi.python.org/pypi/azure-common>`_ >= 1.1.8 * `azure-mgmt <https://pypi.python.org/pypi/azure-mgmt>`_ >= 1.0.0 * `azure-mgmt-compute <https://pypi.python.org/pypi/azure-mgmt-compute>`_ >= 1.0.0 * `azure-mgmt-dns <https://pypi.python.org/pypi/azure-mgmt-dns>`_ >= 2.0.0rc1 * `azure-mgmt-network <https://pypi.python.org/pypi/azure-mgmt-network>`_ >= 1.7.1 * `azure-mgmt-resource <https://pypi.python.org/pypi/azure-mgmt-resource>`_ >= 1.1.0 * `azure-mgmt-storage <https://pypi.python.org/pypi/azure-mgmt-storage>`_ >= 1.0.0 * `azure-mgmt-web <https://pypi.python.org/pypi/azure-mgmt-web>`_ >= 0.32.0 * `azure-storage <https://pypi.python.org/pypi/azure-storage>`_ >= 0.34.3 * `msrestazure <https://pypi.python.org/pypi/msrestazure>`_ >= 0.4.21 :platform: linux :configuration: This module requires Azure Resource Manager credentials to be passed as keyword arguments to every function in order to work properly. Required provider parameters: if using username and password: * ``subscription_id`` * ``username`` * ``password`` if using a service principal: * ``subscription_id`` * ``tenant`` * ``client_id`` * ``secret`` Optional provider parameters: **cloud_environment**: Used to point the cloud driver to different API endpoints, such as Azure GovCloud. Possible values: * ``AZURE_PUBLIC_CLOUD`` (default) * ``AZURE_CHINA_CLOUD`` * ``AZURE_US_GOV_CLOUD`` * ``AZURE_GERMAN_CLOUD`` ''' # Python libs from __future__ import absolute_import import logging # Azure libs HAS_LIBS = False try: import azure.mgmt.dns.models # pylint: disable=unused-import from msrest.exceptions import SerializationError from msrestazure.azure_exceptions import CloudError HAS_LIBS = True except ImportError: pass __virtualname__ = 'azurearm_dns' log = logging.getLogger(__name__) def __virtual__(): if not HAS_LIBS: return ( False, 'The following dependencies are required to use the AzureARM modules: ' 'Microsoft Azure SDK for Python >= 2.0rc6, ' 'MS REST Azure (msrestazure) >= 0.4' ) return __virtualname__ def record_set_create_or_update(name, zone_name, resource_group, record_type, **kwargs): ''' .. versionadded:: Fluorine Creates or updates a record set within a DNS zone. :param name: The name of the record set, relative to the name of the zone. :param zone_name: The name of the DNS zone (without a terminating dot). :param resource_group: The name of the resource group. :param record_type: The type of DNS record in this record set. Record sets of type SOA can be updated but not created (they are created when the DNS zone is created). Possible values include: 'A', 'AAAA', 'CAA', 'CNAME', 'MX', 'NS', 'PTR', 'SOA', 'SRV', 'TXT' CLI Example: .. code-block:: bash salt-call azurearm_dns.record_set_create_or_update myhost myzone testgroup A arecords='[{ipv4_address: 10.0.0.1}]' ttl=300 ''' dnsconn = __utils__['azurearm.get_client']('dns', **kwargs) try: record_set_model = __utils__['azurearm.create_object_model']('dns', 'RecordSet', **kwargs) except TypeError as exc: result = {'error': 'The object model could not be built. ({0})'.format(str(exc))} return result try: record_set = dnsconn.record_sets.create_or_update( relative_record_set_name=name, zone_name=zone_name, resource_group_name=resource_group, record_type=record_type, parameters=record_set_model, if_match=kwargs.get('if_match'), if_none_match=kwargs.get('if_none_match') ) result = record_set.as_dict() except CloudError as exc: __utils__['azurearm.log_cloud_error']('dns', str(exc), **kwargs) result = {'error': str(exc)} except SerializationError as exc: result = {'error': 'The object model could not be parsed. ({0})'.format(str(exc))} return result def record_set_delete(name, zone_name, resource_group, record_type, **kwargs): ''' .. versionadded:: Fluorine Deletes a record set from a DNS zone. This operation cannot be undone. :param name: The name of the record set, relative to the name of the zone. :param zone_name: The name of the DNS zone (without a terminating dot). :param resource_group: The name of the resource group. :param record_type: The type of DNS record in this record set. Record sets of type SOA cannot be deleted (they are deleted when the DNS zone is deleted). Possible values include: 'A', 'AAAA', 'CAA', 'CNAME', 'MX', 'NS', 'PTR', 'SOA', 'SRV', 'TXT' CLI Example: .. code-block:: bash salt-call azurearm_dns.record_set_delete myhost myzone testgroup A ''' result = False dnsconn = __utils__['azurearm.get_client']('dns', **kwargs) try: record_set = dnsconn.record_sets.delete( relative_record_set_name=name, zone_name=zone_name, resource_group_name=resource_group, record_type=record_type, if_match=kwargs.get('if_match') ) result = True except CloudError as exc: __utils__['azurearm.log_cloud_error']('dns', str(exc), **kwargs) return result def record_set_get(name, zone_name, resource_group, record_type, **kwargs): ''' .. versionadded:: Fluorine Get a dictionary representing a record set's properties. :param name: The name of the record set, relative to the name of the zone. :param zone_name: The name of the DNS zone (without a terminating dot). :param resource_group: The name of the resource group. :param record_type: The type of DNS record in this record set. Possible values include: 'A', 'AAAA', 'CAA', 'CNAME', 'MX', 'NS', 'PTR', 'SOA', 'SRV', 'TXT' CLI Example: .. code-block:: bash salt-call azurearm_dns.record_set_get '@' myzone testgroup SOA ''' dnsconn = __utils__['azurearm.get_client']('dns', **kwargs) try: record_set = dnsconn.record_sets.get( relative_record_set_name=name, zone_name=zone_name, resource_group_name=resource_group, record_type=record_type ) result = record_set.as_dict() except CloudError as exc: __utils__['azurearm.log_cloud_error']('dns', str(exc), **kwargs) result = {'error': str(exc)} return result def record_sets_list_by_type(zone_name, resource_group, record_type, top=None, recordsetnamesuffix=None, **kwargs): ''' .. versionadded:: Fluorine Lists the record sets of a specified type in a DNS zone. :param zone_name: The name of the DNS zone (without a terminating dot). :param resource_group: The name of the resource group. :param record_type: The type of record sets to enumerate. Possible values include: 'A', 'AAAA', 'CAA', 'CNAME', 'MX', 'NS', 'PTR', 'SOA', 'SRV', 'TXT' :param top: The maximum number of record sets to return. If not specified, returns up to 100 record sets. :param recordsetnamesuffix: The suffix label of the record set name that has to be used to filter the record set enumerations. CLI Example: .. code-block:: bash salt-call azurearm_dns.record_sets_list_by_type myzone testgroup SOA ''' result = {} dnsconn = __utils__['azurearm.get_client']('dns', **kwargs) try: record_sets = __utils__['azurearm.paged_object_to_list']( dnsconn.record_sets.list_by_type( zone_name=zone_name, resource_group_name=resource_group, record_type=record_type, top=top, recordsetnamesuffix=recordsetnamesuffix ) ) for record_set in record_sets: result[record_set['name']] = record_set except CloudError as exc: __utils__['azurearm.log_cloud_error']('dns', str(exc), **kwargs) result = {'error': str(exc)} return result def record_sets_list_by_dns_zone(zone_name, resource_group, top=None, recordsetnamesuffix=None, **kwargs): ''' .. versionadded:: Fluorine Lists all record sets in a DNS zone. :param zone_name: The name of the DNS zone (without a terminating dot). :param resource_group: The name of the resource group. :param top: The maximum number of record sets to return. If not specified, returns up to 100 record sets. :param recordsetnamesuffix: The suffix label of the record set name that has to be used to filter the record set enumerations. CLI Example: .. code-block:: bash salt-call azurearm_dns.record_sets_list_by_dns_zone myzone testgroup ''' result = {} dnsconn = __utils__['azurearm.get_client']('dns', **kwargs) try: record_sets = __utils__['azurearm.paged_object_to_list']( dnsconn.record_sets.list_by_dns_zone( zone_name=zone_name, resource_group_name=resource_group, top=top, recordsetnamesuffix=recordsetnamesuffix ) ) for record_set in record_sets: result[record_set['name']] = record_set except CloudError as exc: __utils__['azurearm.log_cloud_error']('dns', str(exc), **kwargs) result = {'error': str(exc)} return result def zone_create_or_update(name, resource_group, **kwargs): ''' .. versionadded:: Fluorine Creates or updates a DNS zone. Does not modify DNS records within the zone. :param name: The name of the DNS zone to create (without a terminating dot). :param resource_group: The name of the resource group. CLI Example: .. code-block:: bash salt-call azurearm_dns.zone_create_or_update myzone testgroup ''' # DNS zones are global objects kwargs['location'] = 'global' dnsconn = __utils__['azurearm.get_client']('dns', **kwargs) # Convert list of ID strings to list of dictionaries with id key. if isinstance(kwargs.get('registration_virtual_networks'), list): kwargs['registration_virtual_networks'] = [{'id': vnet} for vnet in kwargs['registration_virtual_networks']] if isinstance(kwargs.get('resolution_virtual_networks'), list): kwargs['resolution_virtual_networks'] = [{'id': vnet} for vnet in kwargs['resolution_virtual_networks']] try: zone_model = __utils__['azurearm.create_object_model']('dns', 'Zone', **kwargs) except TypeError as exc: result = {'error': 'The object model could not be built. ({0})'.format(str(exc))} return result try: zone = dnsconn.zones.create_or_update( zone_name=name, resource_group_name=resource_group, parameters=zone_model, if_match=kwargs.get('if_match'), if_none_match=kwargs.get('if_none_match') ) result = zone.as_dict() except CloudError as exc: __utils__['azurearm.log_cloud_error']('dns', str(exc), **kwargs) result = {'error': str(exc)} except SerializationError as exc: result = {'error': 'The object model could not be parsed. ({0})'.format(str(exc))} return result def zone_delete(name, resource_group, **kwargs): ''' .. versionadded:: Fluorine Delete a DNS zone within a resource group. :param name: The name of the DNS zone to delete. :param resource_group: The name of the resource group. CLI Example: .. code-block:: bash salt-call azurearm_dns.zone_delete myzone testgroup ''' result = False dnsconn = __utils__['azurearm.get_client']('dns', **kwargs) try: zone = dnsconn.zones.delete( zone_name=name, resource_group_name=resource_group, if_match=kwargs.get('if_match') ) zone.wait() result = True except CloudError as exc: __utils__['azurearm.log_cloud_error']('dns', str(exc), **kwargs) return result def zone_get(name, resource_group, **kwargs): ''' .. versionadded:: Fluorine Get a dictionary representing a DNS zone's properties, but not the record sets within the zone. :param name: The DNS zone to get. :param resource_group: The name of the resource group. CLI Example: .. code-block:: bash salt-call azurearm_dns.zone_get myzone testgroup ''' dnsconn = __utils__['azurearm.get_client']('dns', **kwargs) try: zone = dnsconn.zones.get( zone_name=name, resource_group_name=resource_group ) result = zone.as_dict() except CloudError as exc: __utils__['azurearm.log_cloud_error']('dns', str(exc), **kwargs) result = {'error': str(exc)} return result def zones_list(top=None, **kwargs): ''' .. versionadded:: Fluorine Lists the DNS zones in all resource groups in a subscription. :param top: The maximum number of DNS zones to return. If not specified, returns up to 100 zones. CLI Example: .. code-block:: bash salt-call azurearm_dns.zones_list ''' result = {} dnsconn = __utils__['azurearm.get_client']('dns', **kwargs) try: zones = __utils__['azurearm.paged_object_to_list'](dnsconn.zones.list(top=top)) for zone in zones: result[zone['name']] = zone except CloudError as exc: __utils__['azurearm.log_cloud_error']('dns', str(exc), **kwargs) result = {'error': str(exc)} return result
saltstack/salt
salt/modules/azurearm_dns.py
zones_list
python
def zones_list(top=None, **kwargs): ''' .. versionadded:: Fluorine Lists the DNS zones in all resource groups in a subscription. :param top: The maximum number of DNS zones to return. If not specified, returns up to 100 zones. CLI Example: .. code-block:: bash salt-call azurearm_dns.zones_list ''' result = {} dnsconn = __utils__['azurearm.get_client']('dns', **kwargs) try: zones = __utils__['azurearm.paged_object_to_list'](dnsconn.zones.list(top=top)) for zone in zones: result[zone['name']] = zone except CloudError as exc: __utils__['azurearm.log_cloud_error']('dns', str(exc), **kwargs) result = {'error': str(exc)} return result
.. versionadded:: Fluorine Lists the DNS zones in all resource groups in a subscription. :param top: The maximum number of DNS zones to return. If not specified, returns up to 100 zones. CLI Example: .. code-block:: bash salt-call azurearm_dns.zones_list
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/azurearm_dns.py#L460-L487
null
# -*- coding: utf-8 -*- ''' Azure (ARM) DNS Execution Module .. versionadded:: Fluorine :maintainer: <nicholasmhughes@gmail.com> :maturity: new :depends: * `azure <https://pypi.python.org/pypi/azure>`_ >= 2.0.0 * `azure-common <https://pypi.python.org/pypi/azure-common>`_ >= 1.1.8 * `azure-mgmt <https://pypi.python.org/pypi/azure-mgmt>`_ >= 1.0.0 * `azure-mgmt-compute <https://pypi.python.org/pypi/azure-mgmt-compute>`_ >= 1.0.0 * `azure-mgmt-dns <https://pypi.python.org/pypi/azure-mgmt-dns>`_ >= 2.0.0rc1 * `azure-mgmt-network <https://pypi.python.org/pypi/azure-mgmt-network>`_ >= 1.7.1 * `azure-mgmt-resource <https://pypi.python.org/pypi/azure-mgmt-resource>`_ >= 1.1.0 * `azure-mgmt-storage <https://pypi.python.org/pypi/azure-mgmt-storage>`_ >= 1.0.0 * `azure-mgmt-web <https://pypi.python.org/pypi/azure-mgmt-web>`_ >= 0.32.0 * `azure-storage <https://pypi.python.org/pypi/azure-storage>`_ >= 0.34.3 * `msrestazure <https://pypi.python.org/pypi/msrestazure>`_ >= 0.4.21 :platform: linux :configuration: This module requires Azure Resource Manager credentials to be passed as keyword arguments to every function in order to work properly. Required provider parameters: if using username and password: * ``subscription_id`` * ``username`` * ``password`` if using a service principal: * ``subscription_id`` * ``tenant`` * ``client_id`` * ``secret`` Optional provider parameters: **cloud_environment**: Used to point the cloud driver to different API endpoints, such as Azure GovCloud. Possible values: * ``AZURE_PUBLIC_CLOUD`` (default) * ``AZURE_CHINA_CLOUD`` * ``AZURE_US_GOV_CLOUD`` * ``AZURE_GERMAN_CLOUD`` ''' # Python libs from __future__ import absolute_import import logging # Azure libs HAS_LIBS = False try: import azure.mgmt.dns.models # pylint: disable=unused-import from msrest.exceptions import SerializationError from msrestazure.azure_exceptions import CloudError HAS_LIBS = True except ImportError: pass __virtualname__ = 'azurearm_dns' log = logging.getLogger(__name__) def __virtual__(): if not HAS_LIBS: return ( False, 'The following dependencies are required to use the AzureARM modules: ' 'Microsoft Azure SDK for Python >= 2.0rc6, ' 'MS REST Azure (msrestazure) >= 0.4' ) return __virtualname__ def record_set_create_or_update(name, zone_name, resource_group, record_type, **kwargs): ''' .. versionadded:: Fluorine Creates or updates a record set within a DNS zone. :param name: The name of the record set, relative to the name of the zone. :param zone_name: The name of the DNS zone (without a terminating dot). :param resource_group: The name of the resource group. :param record_type: The type of DNS record in this record set. Record sets of type SOA can be updated but not created (they are created when the DNS zone is created). Possible values include: 'A', 'AAAA', 'CAA', 'CNAME', 'MX', 'NS', 'PTR', 'SOA', 'SRV', 'TXT' CLI Example: .. code-block:: bash salt-call azurearm_dns.record_set_create_or_update myhost myzone testgroup A arecords='[{ipv4_address: 10.0.0.1}]' ttl=300 ''' dnsconn = __utils__['azurearm.get_client']('dns', **kwargs) try: record_set_model = __utils__['azurearm.create_object_model']('dns', 'RecordSet', **kwargs) except TypeError as exc: result = {'error': 'The object model could not be built. ({0})'.format(str(exc))} return result try: record_set = dnsconn.record_sets.create_or_update( relative_record_set_name=name, zone_name=zone_name, resource_group_name=resource_group, record_type=record_type, parameters=record_set_model, if_match=kwargs.get('if_match'), if_none_match=kwargs.get('if_none_match') ) result = record_set.as_dict() except CloudError as exc: __utils__['azurearm.log_cloud_error']('dns', str(exc), **kwargs) result = {'error': str(exc)} except SerializationError as exc: result = {'error': 'The object model could not be parsed. ({0})'.format(str(exc))} return result def record_set_delete(name, zone_name, resource_group, record_type, **kwargs): ''' .. versionadded:: Fluorine Deletes a record set from a DNS zone. This operation cannot be undone. :param name: The name of the record set, relative to the name of the zone. :param zone_name: The name of the DNS zone (without a terminating dot). :param resource_group: The name of the resource group. :param record_type: The type of DNS record in this record set. Record sets of type SOA cannot be deleted (they are deleted when the DNS zone is deleted). Possible values include: 'A', 'AAAA', 'CAA', 'CNAME', 'MX', 'NS', 'PTR', 'SOA', 'SRV', 'TXT' CLI Example: .. code-block:: bash salt-call azurearm_dns.record_set_delete myhost myzone testgroup A ''' result = False dnsconn = __utils__['azurearm.get_client']('dns', **kwargs) try: record_set = dnsconn.record_sets.delete( relative_record_set_name=name, zone_name=zone_name, resource_group_name=resource_group, record_type=record_type, if_match=kwargs.get('if_match') ) result = True except CloudError as exc: __utils__['azurearm.log_cloud_error']('dns', str(exc), **kwargs) return result def record_set_get(name, zone_name, resource_group, record_type, **kwargs): ''' .. versionadded:: Fluorine Get a dictionary representing a record set's properties. :param name: The name of the record set, relative to the name of the zone. :param zone_name: The name of the DNS zone (without a terminating dot). :param resource_group: The name of the resource group. :param record_type: The type of DNS record in this record set. Possible values include: 'A', 'AAAA', 'CAA', 'CNAME', 'MX', 'NS', 'PTR', 'SOA', 'SRV', 'TXT' CLI Example: .. code-block:: bash salt-call azurearm_dns.record_set_get '@' myzone testgroup SOA ''' dnsconn = __utils__['azurearm.get_client']('dns', **kwargs) try: record_set = dnsconn.record_sets.get( relative_record_set_name=name, zone_name=zone_name, resource_group_name=resource_group, record_type=record_type ) result = record_set.as_dict() except CloudError as exc: __utils__['azurearm.log_cloud_error']('dns', str(exc), **kwargs) result = {'error': str(exc)} return result def record_sets_list_by_type(zone_name, resource_group, record_type, top=None, recordsetnamesuffix=None, **kwargs): ''' .. versionadded:: Fluorine Lists the record sets of a specified type in a DNS zone. :param zone_name: The name of the DNS zone (without a terminating dot). :param resource_group: The name of the resource group. :param record_type: The type of record sets to enumerate. Possible values include: 'A', 'AAAA', 'CAA', 'CNAME', 'MX', 'NS', 'PTR', 'SOA', 'SRV', 'TXT' :param top: The maximum number of record sets to return. If not specified, returns up to 100 record sets. :param recordsetnamesuffix: The suffix label of the record set name that has to be used to filter the record set enumerations. CLI Example: .. code-block:: bash salt-call azurearm_dns.record_sets_list_by_type myzone testgroup SOA ''' result = {} dnsconn = __utils__['azurearm.get_client']('dns', **kwargs) try: record_sets = __utils__['azurearm.paged_object_to_list']( dnsconn.record_sets.list_by_type( zone_name=zone_name, resource_group_name=resource_group, record_type=record_type, top=top, recordsetnamesuffix=recordsetnamesuffix ) ) for record_set in record_sets: result[record_set['name']] = record_set except CloudError as exc: __utils__['azurearm.log_cloud_error']('dns', str(exc), **kwargs) result = {'error': str(exc)} return result def record_sets_list_by_dns_zone(zone_name, resource_group, top=None, recordsetnamesuffix=None, **kwargs): ''' .. versionadded:: Fluorine Lists all record sets in a DNS zone. :param zone_name: The name of the DNS zone (without a terminating dot). :param resource_group: The name of the resource group. :param top: The maximum number of record sets to return. If not specified, returns up to 100 record sets. :param recordsetnamesuffix: The suffix label of the record set name that has to be used to filter the record set enumerations. CLI Example: .. code-block:: bash salt-call azurearm_dns.record_sets_list_by_dns_zone myzone testgroup ''' result = {} dnsconn = __utils__['azurearm.get_client']('dns', **kwargs) try: record_sets = __utils__['azurearm.paged_object_to_list']( dnsconn.record_sets.list_by_dns_zone( zone_name=zone_name, resource_group_name=resource_group, top=top, recordsetnamesuffix=recordsetnamesuffix ) ) for record_set in record_sets: result[record_set['name']] = record_set except CloudError as exc: __utils__['azurearm.log_cloud_error']('dns', str(exc), **kwargs) result = {'error': str(exc)} return result def zone_create_or_update(name, resource_group, **kwargs): ''' .. versionadded:: Fluorine Creates or updates a DNS zone. Does not modify DNS records within the zone. :param name: The name of the DNS zone to create (without a terminating dot). :param resource_group: The name of the resource group. CLI Example: .. code-block:: bash salt-call azurearm_dns.zone_create_or_update myzone testgroup ''' # DNS zones are global objects kwargs['location'] = 'global' dnsconn = __utils__['azurearm.get_client']('dns', **kwargs) # Convert list of ID strings to list of dictionaries with id key. if isinstance(kwargs.get('registration_virtual_networks'), list): kwargs['registration_virtual_networks'] = [{'id': vnet} for vnet in kwargs['registration_virtual_networks']] if isinstance(kwargs.get('resolution_virtual_networks'), list): kwargs['resolution_virtual_networks'] = [{'id': vnet} for vnet in kwargs['resolution_virtual_networks']] try: zone_model = __utils__['azurearm.create_object_model']('dns', 'Zone', **kwargs) except TypeError as exc: result = {'error': 'The object model could not be built. ({0})'.format(str(exc))} return result try: zone = dnsconn.zones.create_or_update( zone_name=name, resource_group_name=resource_group, parameters=zone_model, if_match=kwargs.get('if_match'), if_none_match=kwargs.get('if_none_match') ) result = zone.as_dict() except CloudError as exc: __utils__['azurearm.log_cloud_error']('dns', str(exc), **kwargs) result = {'error': str(exc)} except SerializationError as exc: result = {'error': 'The object model could not be parsed. ({0})'.format(str(exc))} return result def zone_delete(name, resource_group, **kwargs): ''' .. versionadded:: Fluorine Delete a DNS zone within a resource group. :param name: The name of the DNS zone to delete. :param resource_group: The name of the resource group. CLI Example: .. code-block:: bash salt-call azurearm_dns.zone_delete myzone testgroup ''' result = False dnsconn = __utils__['azurearm.get_client']('dns', **kwargs) try: zone = dnsconn.zones.delete( zone_name=name, resource_group_name=resource_group, if_match=kwargs.get('if_match') ) zone.wait() result = True except CloudError as exc: __utils__['azurearm.log_cloud_error']('dns', str(exc), **kwargs) return result def zone_get(name, resource_group, **kwargs): ''' .. versionadded:: Fluorine Get a dictionary representing a DNS zone's properties, but not the record sets within the zone. :param name: The DNS zone to get. :param resource_group: The name of the resource group. CLI Example: .. code-block:: bash salt-call azurearm_dns.zone_get myzone testgroup ''' dnsconn = __utils__['azurearm.get_client']('dns', **kwargs) try: zone = dnsconn.zones.get( zone_name=name, resource_group_name=resource_group ) result = zone.as_dict() except CloudError as exc: __utils__['azurearm.log_cloud_error']('dns', str(exc), **kwargs) result = {'error': str(exc)} return result def zones_list_by_resource_group(resource_group, top=None, **kwargs): ''' .. versionadded:: Fluorine Lists the DNS zones in a resource group. :param resource_group: The name of the resource group. :param top: The maximum number of DNS zones to return. If not specified, returns up to 100 zones. CLI Example: .. code-block:: bash salt-call azurearm_dns.zones_list_by_resource_group testgroup ''' result = {} dnsconn = __utils__['azurearm.get_client']('dns', **kwargs) try: zones = __utils__['azurearm.paged_object_to_list']( dnsconn.zones.list_by_resource_group( resource_group_name=resource_group, top=top ) ) for zone in zones: result[zone['name']] = zone except CloudError as exc: __utils__['azurearm.log_cloud_error']('dns', str(exc), **kwargs) result = {'error': str(exc)} return result
saltstack/salt
salt/modules/boto_elb.py
exists
python
def exists(name, region=None, key=None, keyid=None, profile=None): ''' Check to see if an ELB exists. CLI example: .. code-block:: bash salt myminion boto_elb.exists myelb region=us-east-1 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: elb = conn.get_all_load_balancers(load_balancer_names=[name]) if elb: return True else: log.debug('The load balancer does not exist in region %s', region) return False except boto.exception.BotoServerError as error: log.warning(error) return False
Check to see if an ELB exists. CLI example: .. code-block:: bash salt myminion boto_elb.exists myelb region=us-east-1
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_elb.py#L90-L111
null
# -*- coding: utf-8 -*- ''' Connection module for Amazon ELB .. versionadded:: 2014.7.0 :configuration: This module accepts explicit elb credentials but can also utilize IAM roles assigned to the instance through Instance Profiles. Dynamic credentials are then automatically obtained from AWS API and no further configuration is necessary. More Information available at: .. code-block:: text http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/iam-roles-for-amazon-ec2.html If IAM roles are not used you need to specify them either in a pillar or in the minion's config file: .. code-block:: yaml elb.keyid: GKTADJGHEIQSXMKKRBJ08H elb.key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs A region may also be specified in the configuration: .. code-block:: yaml elb.region: us-east-1 If a region is not specified, the default is us-east-1. It's also possible to specify key, keyid and region via a profile, either as a passed in dict, or as a string to pull from pillars or minion config: .. code-block:: yaml myprofile: keyid: GKTADJGHEIQSXMKKRBJ08H key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs region: us-east-1 :depends: boto >= 2.33.0 ''' # keep lint from choking on _get_conn and _cache_id # pylint: disable=E0602 from __future__ import absolute_import, print_function, unicode_literals # Import Python libs import logging import time log = logging.getLogger(__name__) # Import Salt libs import salt.utils.json import salt.utils.odict as odict import salt.utils.versions # Import third party libs from salt.ext import six try: import boto import boto.ec2 # pylint: enable=unused-import from boto.ec2.elb import HealthCheck from boto.ec2.elb.attributes import AccessLogAttribute from boto.ec2.elb.attributes import ConnectionDrainingAttribute from boto.ec2.elb.attributes import ConnectionSettingAttribute from boto.ec2.elb.attributes import CrossZoneLoadBalancingAttribute logging.getLogger('boto').setLevel(logging.CRITICAL) HAS_BOTO = True except ImportError: HAS_BOTO = False def __virtual__(): ''' Only load if boto libraries exist. ''' # connection settings were added in 2.33.0 has_boto_reqs = salt.utils.versions.check_boto_reqs( boto_ver='2.33.0', check_boto3=False ) if has_boto_reqs is True: __utils__['boto.assign_funcs'](__name__, 'elb', module='ec2.elb', pack=__salt__) return has_boto_reqs def get_all_elbs(region=None, key=None, keyid=None, profile=None): ''' Return all load balancers associated with an account CLI example: .. code-block:: bash salt myminion boto_elb.get_all_elbs region=us-east-1 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: return [e for e in conn.get_all_load_balancers()] except boto.exception.BotoServerError as error: log.warning(error) return [] def list_elbs(region=None, key=None, keyid=None, profile=None): ''' Return names of all load balancers associated with an account CLI example: .. code-block:: bash salt myminion boto_elb.list_elbs region=us-east-1 ''' return [e.name for e in get_all_elbs(region=region, key=key, keyid=keyid, profile=profile)] def get_elb_config(name, region=None, key=None, keyid=None, profile=None): ''' Get an ELB configuration. CLI example: .. code-block:: bash salt myminion boto_elb.exists myelb region=us-east-1 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) retries = 30 while retries: try: lb = conn.get_all_load_balancers(load_balancer_names=[name]) lb = lb[0] ret = {} ret['availability_zones'] = lb.availability_zones listeners = [] for _listener in lb.listeners: listener_dict = {} listener_dict['elb_port'] = _listener.load_balancer_port listener_dict['elb_protocol'] = _listener.protocol listener_dict['instance_port'] = _listener.instance_port listener_dict['instance_protocol'] = _listener.instance_protocol listener_dict['policies'] = _listener.policy_names if _listener.ssl_certificate_id: listener_dict['certificate'] = _listener.ssl_certificate_id listeners.append(listener_dict) ret['listeners'] = listeners backends = [] for _backend in lb.backends: bs_dict = {} bs_dict['instance_port'] = _backend.instance_port bs_dict['policies'] = [p.policy_name for p in _backend.policies] backends.append(bs_dict) ret['backends'] = backends ret['subnets'] = lb.subnets ret['security_groups'] = lb.security_groups ret['scheme'] = lb.scheme ret['dns_name'] = lb.dns_name ret['tags'] = _get_all_tags(conn, name) lb_policy_lists = [ lb.policies.app_cookie_stickiness_policies, lb.policies.lb_cookie_stickiness_policies, lb.policies.other_policies ] policies = [] for policy_list in lb_policy_lists: policies += [p.policy_name for p in policy_list] ret['policies'] = policies return ret except boto.exception.BotoServerError as error: if error.error_code == 'Throttling': log.debug('Throttled by AWS API, will retry in 5 seconds.') time.sleep(5) retries -= 1 continue log.error('Error fetching config for ELB %s: %s', name, error.message) log.error(error) return {} return {} def listener_dict_to_tuple(listener): ''' Convert an ELB listener dict into a listener tuple used by certain parts of the AWS ELB API. CLI example: .. code-block:: bash salt myminion boto_elb.listener_dict_to_tuple '{"elb_port":80,"instance_port":80,"elb_protocol":"HTTP"}' ''' # We define all listeners as complex listeners. if 'instance_protocol' not in listener: instance_protocol = listener['elb_protocol'].upper() else: instance_protocol = listener['instance_protocol'].upper() listener_tuple = [listener['elb_port'], listener['instance_port'], listener['elb_protocol'], instance_protocol] if 'certificate' in listener: listener_tuple.append(listener['certificate']) return tuple(listener_tuple) def create(name, availability_zones, listeners, subnets=None, security_groups=None, scheme='internet-facing', region=None, key=None, keyid=None, profile=None): ''' Create an ELB CLI example to create an ELB: .. code-block:: bash salt myminion boto_elb.create myelb '["us-east-1a", "us-east-1e"]' '{"elb_port": 443, "elb_protocol": "HTTPS", ...}' region=us-east-1 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if exists(name, region, key, keyid, profile): return True if isinstance(availability_zones, six.string_types): availability_zones = salt.utils.json.loads(availability_zones) if isinstance(listeners, six.string_types): listeners = salt.utils.json.loads(listeners) _complex_listeners = [] for listener in listeners: _complex_listeners.append(listener_dict_to_tuple(listener)) try: lb = conn.create_load_balancer(name=name, zones=availability_zones, subnets=subnets, security_groups=security_groups, scheme=scheme, complex_listeners=_complex_listeners) if lb: log.info('Created ELB %s', name) return True else: log.error('Failed to create ELB %s', name) return False except boto.exception.BotoServerError as error: log.error('Failed to create ELB %s: %s: %s', name, error.error_code, error.message, exc_info_on_loglevel=logging.DEBUG) return False def delete(name, region=None, key=None, keyid=None, profile=None): ''' Delete an ELB. CLI example to delete an ELB: .. code-block:: bash salt myminion boto_elb.delete myelb region=us-east-1 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not exists(name, region, key, keyid, profile): return True try: conn.delete_load_balancer(name) log.info('Deleted ELB %s.', name) return True except boto.exception.BotoServerError as error: log.error('Failed to delete ELB %s', name, exc_info_on_loglevel=logging.DEBUG) return False def create_listeners(name, listeners, region=None, key=None, keyid=None, profile=None): ''' Create listeners on an ELB. CLI example: .. code-block:: bash salt myminion boto_elb.create_listeners myelb '[["HTTPS", "HTTP", 443, 80, "arn:aws:iam::11 11111:server-certificate/mycert"]]' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if isinstance(listeners, six.string_types): listeners = salt.utils.json.loads(listeners) _complex_listeners = [] for listener in listeners: _complex_listeners.append(listener_dict_to_tuple(listener)) try: conn.create_load_balancer_listeners(name, [], _complex_listeners) log.info('Created ELB listeners on %s', name) return True except boto.exception.BotoServerError as error: log.error('Failed to create ELB listeners on %s: %s', name, error, exc_info_on_loglevel=logging.DEBUG) return False def delete_listeners(name, ports, region=None, key=None, keyid=None, profile=None): ''' Delete listeners on an ELB. CLI example: .. code-block:: bash salt myminion boto_elb.delete_listeners myelb '[80,443]' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if isinstance(ports, six.string_types): ports = salt.utils.json.loads(ports) try: conn.delete_load_balancer_listeners(name, ports) log.info('Deleted ELB listeners on %s', name) return True except boto.exception.BotoServerError as error: log.error('Failed to delete ELB listeners on %s: %s', name, error, exc_info_on_loglevel=logging.DEBUG) return False def apply_security_groups(name, security_groups, region=None, key=None, keyid=None, profile=None): ''' Apply security groups to ELB. CLI example: .. code-block:: bash salt myminion boto_elb.apply_security_groups myelb '["mysecgroup1"]' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if isinstance(security_groups, six.string_types): security_groups = salt.utils.json.loads(security_groups) try: conn.apply_security_groups_to_lb(name, security_groups) log.info('Applied security_groups on ELB %s', name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to appply security_groups on ELB %s: %s', name, e.message) return False def enable_availability_zones(name, availability_zones, region=None, key=None, keyid=None, profile=None): ''' Enable availability zones for ELB. CLI example: .. code-block:: bash salt myminion boto_elb.enable_availability_zones myelb '["us-east-1a"]' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if isinstance(availability_zones, six.string_types): availability_zones = salt.utils.json.loads(availability_zones) try: conn.enable_availability_zones(name, availability_zones) log.info('Enabled availability_zones on ELB %s', name) return True except boto.exception.BotoServerError as error: log.error('Failed to enable availability_zones on ELB %s: %s', name, error) return False def disable_availability_zones(name, availability_zones, region=None, key=None, keyid=None, profile=None): ''' Disable availability zones for ELB. CLI example: .. code-block:: bash salt myminion boto_elb.disable_availability_zones myelb '["us-east-1a"]' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if isinstance(availability_zones, six.string_types): availability_zones = salt.utils.json.loads(availability_zones) try: conn.disable_availability_zones(name, availability_zones) log.info('Disabled availability_zones on ELB %s', name) return True except boto.exception.BotoServerError as error: log.error('Failed to disable availability_zones on ELB %s: %s', name, error, exc_info_on_loglevel=logging.DEBUG) return False def attach_subnets(name, subnets, region=None, key=None, keyid=None, profile=None): ''' Attach ELB to subnets. CLI example: .. code-block:: bash salt myminion boto_elb.attach_subnets myelb '["mysubnet"]' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if isinstance(subnets, six.string_types): subnets = salt.utils.json.loads(subnets) try: conn.attach_lb_to_subnets(name, subnets) log.info('Attached ELB %s on subnets.', name) return True except boto.exception.BotoServerError as error: log.error('Failed to attach ELB %s on subnets: %s', name, error, exc_info_on_loglevel=logging.DEBUG) return False def detach_subnets(name, subnets, region=None, key=None, keyid=None, profile=None): ''' Detach ELB from subnets. CLI example: .. code-block:: bash salt myminion boto_elb.detach_subnets myelb '["mysubnet"]' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if isinstance(subnets, six.string_types): subnets = salt.utils.json.loads(subnets) try: conn.detach_lb_from_subnets(name, subnets) log.info('Detached ELB %s from subnets.', name) return True except boto.exception.BotoServerError as error: log.error('Failed to detach ELB %s from subnets: %s', name, error, exc_info_on_loglevel=logging.DEBUG) return False def get_attributes(name, region=None, key=None, keyid=None, profile=None): ''' Check to see if attributes are set on an ELB. CLI example: .. code-block:: bash salt myminion boto_elb.get_attributes myelb ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) retries = 30 while retries: try: lbattrs = conn.get_all_lb_attributes(name) ret = odict.OrderedDict() ret['access_log'] = odict.OrderedDict() ret['cross_zone_load_balancing'] = odict.OrderedDict() ret['connection_draining'] = odict.OrderedDict() ret['connecting_settings'] = odict.OrderedDict() al = lbattrs.access_log czlb = lbattrs.cross_zone_load_balancing cd = lbattrs.connection_draining cs = lbattrs.connecting_settings ret['access_log']['enabled'] = al.enabled ret['access_log']['s3_bucket_name'] = al.s3_bucket_name ret['access_log']['s3_bucket_prefix'] = al.s3_bucket_prefix ret['access_log']['emit_interval'] = al.emit_interval ret['cross_zone_load_balancing']['enabled'] = czlb.enabled ret['connection_draining']['enabled'] = cd.enabled ret['connection_draining']['timeout'] = cd.timeout ret['connecting_settings']['idle_timeout'] = cs.idle_timeout return ret except boto.exception.BotoServerError as e: if e.error_code == 'Throttling': log.debug("Throttled by AWS API, will retry in 5 seconds...") time.sleep(5) retries -= 1 continue log.error('ELB %s does not exist: %s', name, e.message) return {} return {} def set_attributes(name, attributes, region=None, key=None, keyid=None, profile=None): ''' Set attributes on an ELB. name (string) Name of the ELB instance to set attributes for attributes A dict of attributes to set. Valid attributes are: access_log (dict) enabled (bool) Enable storage of access logs. s3_bucket_name (string) The name of the S3 bucket to place logs. s3_bucket_prefix (string) Prefix for the log file name. emit_interval (int) Interval for storing logs in S3 in minutes. Valid values are 5 and 60. connection_draining (dict) enabled (bool) Enable connection draining. timeout (int) Maximum allowed time in seconds for sending existing connections to an instance that is deregistering or unhealthy. Default is 300. cross_zone_load_balancing (dict) enabled (bool) Enable cross-zone load balancing. CLI example to set attributes on an ELB: .. code-block:: bash salt myminion boto_elb.set_attributes myelb '{"access_log": {"enabled": "true", "s3_bucket_name": "mybucket", "s3_bucket_prefix": "mylogs/", "emit_interval": "5"}}' region=us-east-1 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) al = attributes.get('access_log', {}) czlb = attributes.get('cross_zone_load_balancing', {}) cd = attributes.get('connection_draining', {}) cs = attributes.get('connecting_settings', {}) if not al and not czlb and not cd and not cs: log.error('No supported attributes for ELB.') return False if al: _al = AccessLogAttribute() _al.enabled = al.get('enabled', False) if not _al.enabled: msg = 'Access log attribute configured, but enabled config missing' log.error(msg) return False _al.s3_bucket_name = al.get('s3_bucket_name', None) _al.s3_bucket_prefix = al.get('s3_bucket_prefix', None) _al.emit_interval = al.get('emit_interval', None) added_attr = conn.modify_lb_attribute(name, 'accessLog', _al) if added_attr: log.info('Added access_log attribute to %s elb.', name) else: log.error('Failed to add access_log attribute to %s elb.', name) return False if czlb: _czlb = CrossZoneLoadBalancingAttribute() _czlb.enabled = czlb['enabled'] added_attr = conn.modify_lb_attribute(name, 'crossZoneLoadBalancing', _czlb.enabled) if added_attr: log.info('Added cross_zone_load_balancing attribute to %s elb.', name) else: log.error('Failed to add cross_zone_load_balancing attribute.') return False if cd: _cd = ConnectionDrainingAttribute() _cd.enabled = cd['enabled'] _cd.timeout = cd.get('timeout', 300) added_attr = conn.modify_lb_attribute(name, 'connectionDraining', _cd) if added_attr: log.info('Added connection_draining attribute to %s elb.', name) else: log.error('Failed to add connection_draining attribute.') return False if cs: _cs = ConnectionSettingAttribute() _cs.idle_timeout = cs.get('idle_timeout', 60) added_attr = conn.modify_lb_attribute(name, 'connectingSettings', _cs) if added_attr: log.info('Added connecting_settings attribute to %s elb.', name) else: log.error('Failed to add connecting_settings attribute.') return False return True def get_health_check(name, region=None, key=None, keyid=None, profile=None): ''' Get the health check configured for this ELB. CLI example: .. code-block:: bash salt myminion boto_elb.get_health_check myelb ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) retries = 30 while True: try: lb = conn.get_all_load_balancers(load_balancer_names=[name]) lb = lb[0] ret = odict.OrderedDict() hc = lb.health_check ret['interval'] = hc.interval ret['target'] = hc.target ret['healthy_threshold'] = hc.healthy_threshold ret['timeout'] = hc.timeout ret['unhealthy_threshold'] = hc.unhealthy_threshold return ret except boto.exception.BotoServerError as e: if retries and e.code == 'Throttling': log.debug('Throttled by AWS API, will retry in 5 seconds.') time.sleep(5) retries -= 1 continue log.error('ELB %s not found.', name, exc_info_on_logleve=logging.DEBUG) return {} def set_health_check(name, health_check, region=None, key=None, keyid=None, profile=None): ''' Set attributes on an ELB. CLI example to set attributes on an ELB: .. code-block:: bash salt myminion boto_elb.set_health_check myelb '{"target": "HTTP:80/"}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) retries = 30 hc = HealthCheck(**health_check) while True: try: conn.configure_health_check(name, hc) log.info('Configured health check on ELB %s', name) return True except boto.exception.BotoServerError as error: if retries and e.code == 'Throttling': log.debug('Throttled by AWS API, will retry in 5 seconds.') time.sleep(5) retries -= 1 continue log.exception('Failed to configure health check on ELB %s', name) return False def register_instances(name, instances, region=None, key=None, keyid=None, profile=None): ''' Register instances with an ELB. Instances is either a string instance id or a list of string instance id's. Returns: - ``True``: instance(s) registered successfully - ``False``: instance(s) failed to be registered CLI example: .. code-block:: bash salt myminion boto_elb.register_instances myelb instance_id salt myminion boto_elb.register_instances myelb "[instance_id,instance_id]" ''' # convert instances to list type, enabling consistent use of instances # variable throughout the register_instances method if isinstance(instances, six.string_types) or isinstance(instances, six.text_type): instances = [instances] conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: registered_instances = conn.register_instances(name, instances) except boto.exception.BotoServerError as error: log.warning(error) return False registered_instance_ids = [instance.id for instance in registered_instances] # register_failues is a set that will contain any instances that were not # able to be registered with the given ELB register_failures = set(instances).difference(set(registered_instance_ids)) if register_failures: log.warning('Instance(s): %s not registered with ELB %s.', list(register_failures), name) register_result = False else: register_result = True return register_result def deregister_instances(name, instances, region=None, key=None, keyid=None, profile=None): ''' Deregister instances with an ELB. Instances is either a string instance id or a list of string instance id's. Returns: - ``True``: instance(s) deregistered successfully - ``False``: instance(s) failed to be deregistered - ``None``: instance(s) not valid or not registered, no action taken CLI example: .. code-block:: bash salt myminion boto_elb.deregister_instances myelb instance_id salt myminion boto_elb.deregister_instances myelb "[instance_id, instance_id]" ''' # convert instances to list type, enabling consistent use of instances # variable throughout the deregister_instances method if isinstance(instances, six.string_types) or isinstance(instances, six.text_type): instances = [instances] conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: registered_instances = conn.deregister_instances(name, instances) except boto.exception.BotoServerError as error: # if the instance(s) given as an argument are not members of the ELB # boto returns error.error_code == 'InvalidInstance' # deregister_instances returns "None" because the instances are # effectively deregistered from ELB if error.error_code == 'InvalidInstance': log.warning( 'One or more of instance(s) %s are not part of ELB %s. ' 'deregister_instances not performed.', instances, name ) return None else: log.warning(error) return False registered_instance_ids = [instance.id for instance in registered_instances] # deregister_failures is a set that will contain any instances that were # unable to be deregistered from the given ELB deregister_failures = set(instances).intersection(set(registered_instance_ids)) if deregister_failures: log.warning( 'Instance(s): %s not deregistered from ELB %s.', list(deregister_failures), name ) deregister_result = False else: deregister_result = True return deregister_result def set_instances(name, instances, test=False, region=None, key=None, keyid=None, profile=None): ''' Set the instances assigned to an ELB to exactly the list given CLI example: .. code-block:: bash salt myminion boto_elb.set_instances myelb region=us-east-1 instances="[instance_id,instance_id]" ''' ret = True current = set([i['instance_id'] for i in get_instance_health(name, region, key, keyid, profile)]) desired = set(instances) add = desired - current remove = current - desired if test: return bool(add or remove) if remove: if deregister_instances(name, list(remove), region, key, keyid, profile) is False: ret = False if add: if register_instances(name, list(add), region, key, keyid, profile) is False: ret = False return ret def get_instance_health(name, region=None, key=None, keyid=None, profile=None, instances=None): ''' Get a list of instances and their health state CLI example: .. code-block:: bash salt myminion boto_elb.get_instance_health myelb salt myminion boto_elb.get_instance_health myelb region=us-east-1 instances="[instance_id,instance_id]" ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: instance_states = conn.describe_instance_health(name, instances) ret = [] for _instance in instance_states: ret.append({'instance_id': _instance.instance_id, 'description': _instance.description, 'state': _instance.state, 'reason_code': _instance.reason_code }) return ret except boto.exception.BotoServerError as error: log.debug(error) return [] def create_policy(name, policy_name, policy_type, policy, region=None, key=None, keyid=None, profile=None): ''' Create an ELB policy. .. versionadded:: 2016.3.0 CLI example: .. code-block:: bash salt myminion boto_elb.create_policy myelb mypolicy LBCookieStickinessPolicyType '{"CookieExpirationPeriod": 3600}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not exists(name, region, key, keyid, profile): return False try: success = conn.create_lb_policy(name, policy_name, policy_type, policy) if success: log.info('Created policy %s on ELB %s', policy_name, name) return True else: log.error('Failed to create policy %s on ELB %s', policy_name, name) return False except boto.exception.BotoServerError as e: log.error('Failed to create policy %s on ELB %s: %s', policy_name, name, e.message, exc_info_on_loglevel=logging.DEBUG) return False def delete_policy(name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Delete an ELB policy. .. versionadded:: 2016.3.0 CLI example: .. code-block:: bash salt myminion boto_elb.delete_policy myelb mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not exists(name, region, key, keyid, profile): return True try: conn.delete_lb_policy(name, policy_name) log.info('Deleted policy %s on ELB %s', policy_name, name) return True except boto.exception.BotoServerError as e: log.error('Failed to delete policy %s on ELB %s: %s', policy_name, name, e.message, exc_info_on_loglevel=logging.DEBUG) return False def set_listener_policy(name, port, policies=None, region=None, key=None, keyid=None, profile=None): ''' Set the policies of an ELB listener. .. versionadded:: 2016.3.0 CLI example: .. code-block:: Bash salt myminion boto_elb.set_listener_policy myelb 443 "[policy1,policy2]" ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not exists(name, region, key, keyid, profile): return True if policies is None: policies = [] try: conn.set_lb_policies_of_listener(name, port, policies) log.info('Set policies %s on ELB %s listener %s', policies, name, port) except boto.exception.BotoServerError as e: log.info('Failed to set policy %s on ELB %s listener %s: %s', policies, name, port, e.message, exc_info_on_loglevel=logging.DEBUG) return False return True def set_backend_policy(name, port, policies=None, region=None, key=None, keyid=None, profile=None): ''' Set the policies of an ELB backend server. CLI example: salt myminion boto_elb.set_backend_policy myelb 443 "[policy1,policy2]" ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not exists(name, region, key, keyid, profile): return True if policies is None: policies = [] try: conn.set_lb_policies_of_backend_server(name, port, policies) log.info('Set policies %s on ELB %s backend server %s', policies, name, port) except boto.exception.BotoServerError as e: log.info('Failed to set policy %s on ELB %s backend server %s: %s', policies, name, port, e.message, exc_info_on_loglevel=logging.DEBUG) return False return True def set_tags(name, tags, region=None, key=None, keyid=None, profile=None): ''' Add the tags on an ELB .. versionadded:: 2016.3.0 name name of the ELB tags dict of name/value pair tags CLI Example: .. code-block:: bash salt myminion boto_elb.set_tags my-elb-name "{'Tag1': 'Value', 'Tag2': 'Another Value'}" ''' if exists(name, region, key, keyid, profile): conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) ret = _add_tags(conn, name, tags) return ret else: return False def delete_tags(name, tags, region=None, key=None, keyid=None, profile=None): ''' Add the tags on an ELB name name of the ELB tags list of tags to remove CLI Example: .. code-block:: bash salt myminion boto_elb.delete_tags my-elb-name ['TagToRemove1', 'TagToRemove2'] ''' if exists(name, region, key, keyid, profile): conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) ret = _remove_tags(conn, name, tags) return ret else: return False def _build_tag_param_list(params, tags): ''' helper function to build a tag parameter list to send ''' keys = sorted(tags.keys()) i = 1 for key in keys: value = tags[key] params['Tags.member.{0}.Key'.format(i)] = key if value is not None: params['Tags.member.{0}.Value'.format(i)] = value i += 1 def _get_all_tags(conn, load_balancer_names=None): ''' Retrieve all the metadata tags associated with your ELB(s). :type load_balancer_names: list :param load_balancer_names: An optional list of load balancer names. :rtype: list :return: A list of :class:`boto.ec2.elb.tag.Tag` objects ''' params = {} if load_balancer_names: conn.build_list_params(params, load_balancer_names, 'LoadBalancerNames.member.%d') tags = conn.get_object( 'DescribeTags', params, __utils__['boto_elb_tag.get_tag_descriptions'](), verb='POST' ) if tags[load_balancer_names]: return tags[load_balancer_names] else: return None def _add_tags(conn, load_balancer_names, tags): ''' Create new metadata tags for the specified resource ids. :type load_balancer_names: list :param load_balancer_names: A list of load balancer names. :type tags: dict :param tags: A dictionary containing the name/value pairs. If you want to create only a tag name, the value for that tag should be the empty string (e.g. ''). ''' params = {} conn.build_list_params(params, load_balancer_names, 'LoadBalancerNames.member.%d') _build_tag_param_list(params, tags) return conn.get_status('AddTags', params, verb='POST') def _remove_tags(conn, load_balancer_names, tags): ''' Delete metadata tags for the specified resource ids. :type load_balancer_names: list :param load_balancer_names: A list of load balancer names. :type tags: list :param tags: A list containing just tag names for the tags to be deleted. ''' params = {} conn.build_list_params(params, load_balancer_names, 'LoadBalancerNames.member.%d') conn.build_list_params(params, tags, 'Tags.member.%d.Key') return conn.get_status('RemoveTags', params, verb='POST')
saltstack/salt
salt/modules/boto_elb.py
get_all_elbs
python
def get_all_elbs(region=None, key=None, keyid=None, profile=None): ''' Return all load balancers associated with an account CLI example: .. code-block:: bash salt myminion boto_elb.get_all_elbs region=us-east-1 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: return [e for e in conn.get_all_load_balancers()] except boto.exception.BotoServerError as error: log.warning(error) return []
Return all load balancers associated with an account CLI example: .. code-block:: bash salt myminion boto_elb.get_all_elbs region=us-east-1
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_elb.py#L114-L130
null
# -*- coding: utf-8 -*- ''' Connection module for Amazon ELB .. versionadded:: 2014.7.0 :configuration: This module accepts explicit elb credentials but can also utilize IAM roles assigned to the instance through Instance Profiles. Dynamic credentials are then automatically obtained from AWS API and no further configuration is necessary. More Information available at: .. code-block:: text http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/iam-roles-for-amazon-ec2.html If IAM roles are not used you need to specify them either in a pillar or in the minion's config file: .. code-block:: yaml elb.keyid: GKTADJGHEIQSXMKKRBJ08H elb.key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs A region may also be specified in the configuration: .. code-block:: yaml elb.region: us-east-1 If a region is not specified, the default is us-east-1. It's also possible to specify key, keyid and region via a profile, either as a passed in dict, or as a string to pull from pillars or minion config: .. code-block:: yaml myprofile: keyid: GKTADJGHEIQSXMKKRBJ08H key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs region: us-east-1 :depends: boto >= 2.33.0 ''' # keep lint from choking on _get_conn and _cache_id # pylint: disable=E0602 from __future__ import absolute_import, print_function, unicode_literals # Import Python libs import logging import time log = logging.getLogger(__name__) # Import Salt libs import salt.utils.json import salt.utils.odict as odict import salt.utils.versions # Import third party libs from salt.ext import six try: import boto import boto.ec2 # pylint: enable=unused-import from boto.ec2.elb import HealthCheck from boto.ec2.elb.attributes import AccessLogAttribute from boto.ec2.elb.attributes import ConnectionDrainingAttribute from boto.ec2.elb.attributes import ConnectionSettingAttribute from boto.ec2.elb.attributes import CrossZoneLoadBalancingAttribute logging.getLogger('boto').setLevel(logging.CRITICAL) HAS_BOTO = True except ImportError: HAS_BOTO = False def __virtual__(): ''' Only load if boto libraries exist. ''' # connection settings were added in 2.33.0 has_boto_reqs = salt.utils.versions.check_boto_reqs( boto_ver='2.33.0', check_boto3=False ) if has_boto_reqs is True: __utils__['boto.assign_funcs'](__name__, 'elb', module='ec2.elb', pack=__salt__) return has_boto_reqs def exists(name, region=None, key=None, keyid=None, profile=None): ''' Check to see if an ELB exists. CLI example: .. code-block:: bash salt myminion boto_elb.exists myelb region=us-east-1 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: elb = conn.get_all_load_balancers(load_balancer_names=[name]) if elb: return True else: log.debug('The load balancer does not exist in region %s', region) return False except boto.exception.BotoServerError as error: log.warning(error) return False def list_elbs(region=None, key=None, keyid=None, profile=None): ''' Return names of all load balancers associated with an account CLI example: .. code-block:: bash salt myminion boto_elb.list_elbs region=us-east-1 ''' return [e.name for e in get_all_elbs(region=region, key=key, keyid=keyid, profile=profile)] def get_elb_config(name, region=None, key=None, keyid=None, profile=None): ''' Get an ELB configuration. CLI example: .. code-block:: bash salt myminion boto_elb.exists myelb region=us-east-1 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) retries = 30 while retries: try: lb = conn.get_all_load_balancers(load_balancer_names=[name]) lb = lb[0] ret = {} ret['availability_zones'] = lb.availability_zones listeners = [] for _listener in lb.listeners: listener_dict = {} listener_dict['elb_port'] = _listener.load_balancer_port listener_dict['elb_protocol'] = _listener.protocol listener_dict['instance_port'] = _listener.instance_port listener_dict['instance_protocol'] = _listener.instance_protocol listener_dict['policies'] = _listener.policy_names if _listener.ssl_certificate_id: listener_dict['certificate'] = _listener.ssl_certificate_id listeners.append(listener_dict) ret['listeners'] = listeners backends = [] for _backend in lb.backends: bs_dict = {} bs_dict['instance_port'] = _backend.instance_port bs_dict['policies'] = [p.policy_name for p in _backend.policies] backends.append(bs_dict) ret['backends'] = backends ret['subnets'] = lb.subnets ret['security_groups'] = lb.security_groups ret['scheme'] = lb.scheme ret['dns_name'] = lb.dns_name ret['tags'] = _get_all_tags(conn, name) lb_policy_lists = [ lb.policies.app_cookie_stickiness_policies, lb.policies.lb_cookie_stickiness_policies, lb.policies.other_policies ] policies = [] for policy_list in lb_policy_lists: policies += [p.policy_name for p in policy_list] ret['policies'] = policies return ret except boto.exception.BotoServerError as error: if error.error_code == 'Throttling': log.debug('Throttled by AWS API, will retry in 5 seconds.') time.sleep(5) retries -= 1 continue log.error('Error fetching config for ELB %s: %s', name, error.message) log.error(error) return {} return {} def listener_dict_to_tuple(listener): ''' Convert an ELB listener dict into a listener tuple used by certain parts of the AWS ELB API. CLI example: .. code-block:: bash salt myminion boto_elb.listener_dict_to_tuple '{"elb_port":80,"instance_port":80,"elb_protocol":"HTTP"}' ''' # We define all listeners as complex listeners. if 'instance_protocol' not in listener: instance_protocol = listener['elb_protocol'].upper() else: instance_protocol = listener['instance_protocol'].upper() listener_tuple = [listener['elb_port'], listener['instance_port'], listener['elb_protocol'], instance_protocol] if 'certificate' in listener: listener_tuple.append(listener['certificate']) return tuple(listener_tuple) def create(name, availability_zones, listeners, subnets=None, security_groups=None, scheme='internet-facing', region=None, key=None, keyid=None, profile=None): ''' Create an ELB CLI example to create an ELB: .. code-block:: bash salt myminion boto_elb.create myelb '["us-east-1a", "us-east-1e"]' '{"elb_port": 443, "elb_protocol": "HTTPS", ...}' region=us-east-1 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if exists(name, region, key, keyid, profile): return True if isinstance(availability_zones, six.string_types): availability_zones = salt.utils.json.loads(availability_zones) if isinstance(listeners, six.string_types): listeners = salt.utils.json.loads(listeners) _complex_listeners = [] for listener in listeners: _complex_listeners.append(listener_dict_to_tuple(listener)) try: lb = conn.create_load_balancer(name=name, zones=availability_zones, subnets=subnets, security_groups=security_groups, scheme=scheme, complex_listeners=_complex_listeners) if lb: log.info('Created ELB %s', name) return True else: log.error('Failed to create ELB %s', name) return False except boto.exception.BotoServerError as error: log.error('Failed to create ELB %s: %s: %s', name, error.error_code, error.message, exc_info_on_loglevel=logging.DEBUG) return False def delete(name, region=None, key=None, keyid=None, profile=None): ''' Delete an ELB. CLI example to delete an ELB: .. code-block:: bash salt myminion boto_elb.delete myelb region=us-east-1 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not exists(name, region, key, keyid, profile): return True try: conn.delete_load_balancer(name) log.info('Deleted ELB %s.', name) return True except boto.exception.BotoServerError as error: log.error('Failed to delete ELB %s', name, exc_info_on_loglevel=logging.DEBUG) return False def create_listeners(name, listeners, region=None, key=None, keyid=None, profile=None): ''' Create listeners on an ELB. CLI example: .. code-block:: bash salt myminion boto_elb.create_listeners myelb '[["HTTPS", "HTTP", 443, 80, "arn:aws:iam::11 11111:server-certificate/mycert"]]' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if isinstance(listeners, six.string_types): listeners = salt.utils.json.loads(listeners) _complex_listeners = [] for listener in listeners: _complex_listeners.append(listener_dict_to_tuple(listener)) try: conn.create_load_balancer_listeners(name, [], _complex_listeners) log.info('Created ELB listeners on %s', name) return True except boto.exception.BotoServerError as error: log.error('Failed to create ELB listeners on %s: %s', name, error, exc_info_on_loglevel=logging.DEBUG) return False def delete_listeners(name, ports, region=None, key=None, keyid=None, profile=None): ''' Delete listeners on an ELB. CLI example: .. code-block:: bash salt myminion boto_elb.delete_listeners myelb '[80,443]' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if isinstance(ports, six.string_types): ports = salt.utils.json.loads(ports) try: conn.delete_load_balancer_listeners(name, ports) log.info('Deleted ELB listeners on %s', name) return True except boto.exception.BotoServerError as error: log.error('Failed to delete ELB listeners on %s: %s', name, error, exc_info_on_loglevel=logging.DEBUG) return False def apply_security_groups(name, security_groups, region=None, key=None, keyid=None, profile=None): ''' Apply security groups to ELB. CLI example: .. code-block:: bash salt myminion boto_elb.apply_security_groups myelb '["mysecgroup1"]' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if isinstance(security_groups, six.string_types): security_groups = salt.utils.json.loads(security_groups) try: conn.apply_security_groups_to_lb(name, security_groups) log.info('Applied security_groups on ELB %s', name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to appply security_groups on ELB %s: %s', name, e.message) return False def enable_availability_zones(name, availability_zones, region=None, key=None, keyid=None, profile=None): ''' Enable availability zones for ELB. CLI example: .. code-block:: bash salt myminion boto_elb.enable_availability_zones myelb '["us-east-1a"]' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if isinstance(availability_zones, six.string_types): availability_zones = salt.utils.json.loads(availability_zones) try: conn.enable_availability_zones(name, availability_zones) log.info('Enabled availability_zones on ELB %s', name) return True except boto.exception.BotoServerError as error: log.error('Failed to enable availability_zones on ELB %s: %s', name, error) return False def disable_availability_zones(name, availability_zones, region=None, key=None, keyid=None, profile=None): ''' Disable availability zones for ELB. CLI example: .. code-block:: bash salt myminion boto_elb.disable_availability_zones myelb '["us-east-1a"]' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if isinstance(availability_zones, six.string_types): availability_zones = salt.utils.json.loads(availability_zones) try: conn.disable_availability_zones(name, availability_zones) log.info('Disabled availability_zones on ELB %s', name) return True except boto.exception.BotoServerError as error: log.error('Failed to disable availability_zones on ELB %s: %s', name, error, exc_info_on_loglevel=logging.DEBUG) return False def attach_subnets(name, subnets, region=None, key=None, keyid=None, profile=None): ''' Attach ELB to subnets. CLI example: .. code-block:: bash salt myminion boto_elb.attach_subnets myelb '["mysubnet"]' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if isinstance(subnets, six.string_types): subnets = salt.utils.json.loads(subnets) try: conn.attach_lb_to_subnets(name, subnets) log.info('Attached ELB %s on subnets.', name) return True except boto.exception.BotoServerError as error: log.error('Failed to attach ELB %s on subnets: %s', name, error, exc_info_on_loglevel=logging.DEBUG) return False def detach_subnets(name, subnets, region=None, key=None, keyid=None, profile=None): ''' Detach ELB from subnets. CLI example: .. code-block:: bash salt myminion boto_elb.detach_subnets myelb '["mysubnet"]' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if isinstance(subnets, six.string_types): subnets = salt.utils.json.loads(subnets) try: conn.detach_lb_from_subnets(name, subnets) log.info('Detached ELB %s from subnets.', name) return True except boto.exception.BotoServerError as error: log.error('Failed to detach ELB %s from subnets: %s', name, error, exc_info_on_loglevel=logging.DEBUG) return False def get_attributes(name, region=None, key=None, keyid=None, profile=None): ''' Check to see if attributes are set on an ELB. CLI example: .. code-block:: bash salt myminion boto_elb.get_attributes myelb ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) retries = 30 while retries: try: lbattrs = conn.get_all_lb_attributes(name) ret = odict.OrderedDict() ret['access_log'] = odict.OrderedDict() ret['cross_zone_load_balancing'] = odict.OrderedDict() ret['connection_draining'] = odict.OrderedDict() ret['connecting_settings'] = odict.OrderedDict() al = lbattrs.access_log czlb = lbattrs.cross_zone_load_balancing cd = lbattrs.connection_draining cs = lbattrs.connecting_settings ret['access_log']['enabled'] = al.enabled ret['access_log']['s3_bucket_name'] = al.s3_bucket_name ret['access_log']['s3_bucket_prefix'] = al.s3_bucket_prefix ret['access_log']['emit_interval'] = al.emit_interval ret['cross_zone_load_balancing']['enabled'] = czlb.enabled ret['connection_draining']['enabled'] = cd.enabled ret['connection_draining']['timeout'] = cd.timeout ret['connecting_settings']['idle_timeout'] = cs.idle_timeout return ret except boto.exception.BotoServerError as e: if e.error_code == 'Throttling': log.debug("Throttled by AWS API, will retry in 5 seconds...") time.sleep(5) retries -= 1 continue log.error('ELB %s does not exist: %s', name, e.message) return {} return {} def set_attributes(name, attributes, region=None, key=None, keyid=None, profile=None): ''' Set attributes on an ELB. name (string) Name of the ELB instance to set attributes for attributes A dict of attributes to set. Valid attributes are: access_log (dict) enabled (bool) Enable storage of access logs. s3_bucket_name (string) The name of the S3 bucket to place logs. s3_bucket_prefix (string) Prefix for the log file name. emit_interval (int) Interval for storing logs in S3 in minutes. Valid values are 5 and 60. connection_draining (dict) enabled (bool) Enable connection draining. timeout (int) Maximum allowed time in seconds for sending existing connections to an instance that is deregistering or unhealthy. Default is 300. cross_zone_load_balancing (dict) enabled (bool) Enable cross-zone load balancing. CLI example to set attributes on an ELB: .. code-block:: bash salt myminion boto_elb.set_attributes myelb '{"access_log": {"enabled": "true", "s3_bucket_name": "mybucket", "s3_bucket_prefix": "mylogs/", "emit_interval": "5"}}' region=us-east-1 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) al = attributes.get('access_log', {}) czlb = attributes.get('cross_zone_load_balancing', {}) cd = attributes.get('connection_draining', {}) cs = attributes.get('connecting_settings', {}) if not al and not czlb and not cd and not cs: log.error('No supported attributes for ELB.') return False if al: _al = AccessLogAttribute() _al.enabled = al.get('enabled', False) if not _al.enabled: msg = 'Access log attribute configured, but enabled config missing' log.error(msg) return False _al.s3_bucket_name = al.get('s3_bucket_name', None) _al.s3_bucket_prefix = al.get('s3_bucket_prefix', None) _al.emit_interval = al.get('emit_interval', None) added_attr = conn.modify_lb_attribute(name, 'accessLog', _al) if added_attr: log.info('Added access_log attribute to %s elb.', name) else: log.error('Failed to add access_log attribute to %s elb.', name) return False if czlb: _czlb = CrossZoneLoadBalancingAttribute() _czlb.enabled = czlb['enabled'] added_attr = conn.modify_lb_attribute(name, 'crossZoneLoadBalancing', _czlb.enabled) if added_attr: log.info('Added cross_zone_load_balancing attribute to %s elb.', name) else: log.error('Failed to add cross_zone_load_balancing attribute.') return False if cd: _cd = ConnectionDrainingAttribute() _cd.enabled = cd['enabled'] _cd.timeout = cd.get('timeout', 300) added_attr = conn.modify_lb_attribute(name, 'connectionDraining', _cd) if added_attr: log.info('Added connection_draining attribute to %s elb.', name) else: log.error('Failed to add connection_draining attribute.') return False if cs: _cs = ConnectionSettingAttribute() _cs.idle_timeout = cs.get('idle_timeout', 60) added_attr = conn.modify_lb_attribute(name, 'connectingSettings', _cs) if added_attr: log.info('Added connecting_settings attribute to %s elb.', name) else: log.error('Failed to add connecting_settings attribute.') return False return True def get_health_check(name, region=None, key=None, keyid=None, profile=None): ''' Get the health check configured for this ELB. CLI example: .. code-block:: bash salt myminion boto_elb.get_health_check myelb ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) retries = 30 while True: try: lb = conn.get_all_load_balancers(load_balancer_names=[name]) lb = lb[0] ret = odict.OrderedDict() hc = lb.health_check ret['interval'] = hc.interval ret['target'] = hc.target ret['healthy_threshold'] = hc.healthy_threshold ret['timeout'] = hc.timeout ret['unhealthy_threshold'] = hc.unhealthy_threshold return ret except boto.exception.BotoServerError as e: if retries and e.code == 'Throttling': log.debug('Throttled by AWS API, will retry in 5 seconds.') time.sleep(5) retries -= 1 continue log.error('ELB %s not found.', name, exc_info_on_logleve=logging.DEBUG) return {} def set_health_check(name, health_check, region=None, key=None, keyid=None, profile=None): ''' Set attributes on an ELB. CLI example to set attributes on an ELB: .. code-block:: bash salt myminion boto_elb.set_health_check myelb '{"target": "HTTP:80/"}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) retries = 30 hc = HealthCheck(**health_check) while True: try: conn.configure_health_check(name, hc) log.info('Configured health check on ELB %s', name) return True except boto.exception.BotoServerError as error: if retries and e.code == 'Throttling': log.debug('Throttled by AWS API, will retry in 5 seconds.') time.sleep(5) retries -= 1 continue log.exception('Failed to configure health check on ELB %s', name) return False def register_instances(name, instances, region=None, key=None, keyid=None, profile=None): ''' Register instances with an ELB. Instances is either a string instance id or a list of string instance id's. Returns: - ``True``: instance(s) registered successfully - ``False``: instance(s) failed to be registered CLI example: .. code-block:: bash salt myminion boto_elb.register_instances myelb instance_id salt myminion boto_elb.register_instances myelb "[instance_id,instance_id]" ''' # convert instances to list type, enabling consistent use of instances # variable throughout the register_instances method if isinstance(instances, six.string_types) or isinstance(instances, six.text_type): instances = [instances] conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: registered_instances = conn.register_instances(name, instances) except boto.exception.BotoServerError as error: log.warning(error) return False registered_instance_ids = [instance.id for instance in registered_instances] # register_failues is a set that will contain any instances that were not # able to be registered with the given ELB register_failures = set(instances).difference(set(registered_instance_ids)) if register_failures: log.warning('Instance(s): %s not registered with ELB %s.', list(register_failures), name) register_result = False else: register_result = True return register_result def deregister_instances(name, instances, region=None, key=None, keyid=None, profile=None): ''' Deregister instances with an ELB. Instances is either a string instance id or a list of string instance id's. Returns: - ``True``: instance(s) deregistered successfully - ``False``: instance(s) failed to be deregistered - ``None``: instance(s) not valid or not registered, no action taken CLI example: .. code-block:: bash salt myminion boto_elb.deregister_instances myelb instance_id salt myminion boto_elb.deregister_instances myelb "[instance_id, instance_id]" ''' # convert instances to list type, enabling consistent use of instances # variable throughout the deregister_instances method if isinstance(instances, six.string_types) or isinstance(instances, six.text_type): instances = [instances] conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: registered_instances = conn.deregister_instances(name, instances) except boto.exception.BotoServerError as error: # if the instance(s) given as an argument are not members of the ELB # boto returns error.error_code == 'InvalidInstance' # deregister_instances returns "None" because the instances are # effectively deregistered from ELB if error.error_code == 'InvalidInstance': log.warning( 'One or more of instance(s) %s are not part of ELB %s. ' 'deregister_instances not performed.', instances, name ) return None else: log.warning(error) return False registered_instance_ids = [instance.id for instance in registered_instances] # deregister_failures is a set that will contain any instances that were # unable to be deregistered from the given ELB deregister_failures = set(instances).intersection(set(registered_instance_ids)) if deregister_failures: log.warning( 'Instance(s): %s not deregistered from ELB %s.', list(deregister_failures), name ) deregister_result = False else: deregister_result = True return deregister_result def set_instances(name, instances, test=False, region=None, key=None, keyid=None, profile=None): ''' Set the instances assigned to an ELB to exactly the list given CLI example: .. code-block:: bash salt myminion boto_elb.set_instances myelb region=us-east-1 instances="[instance_id,instance_id]" ''' ret = True current = set([i['instance_id'] for i in get_instance_health(name, region, key, keyid, profile)]) desired = set(instances) add = desired - current remove = current - desired if test: return bool(add or remove) if remove: if deregister_instances(name, list(remove), region, key, keyid, profile) is False: ret = False if add: if register_instances(name, list(add), region, key, keyid, profile) is False: ret = False return ret def get_instance_health(name, region=None, key=None, keyid=None, profile=None, instances=None): ''' Get a list of instances and their health state CLI example: .. code-block:: bash salt myminion boto_elb.get_instance_health myelb salt myminion boto_elb.get_instance_health myelb region=us-east-1 instances="[instance_id,instance_id]" ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: instance_states = conn.describe_instance_health(name, instances) ret = [] for _instance in instance_states: ret.append({'instance_id': _instance.instance_id, 'description': _instance.description, 'state': _instance.state, 'reason_code': _instance.reason_code }) return ret except boto.exception.BotoServerError as error: log.debug(error) return [] def create_policy(name, policy_name, policy_type, policy, region=None, key=None, keyid=None, profile=None): ''' Create an ELB policy. .. versionadded:: 2016.3.0 CLI example: .. code-block:: bash salt myminion boto_elb.create_policy myelb mypolicy LBCookieStickinessPolicyType '{"CookieExpirationPeriod": 3600}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not exists(name, region, key, keyid, profile): return False try: success = conn.create_lb_policy(name, policy_name, policy_type, policy) if success: log.info('Created policy %s on ELB %s', policy_name, name) return True else: log.error('Failed to create policy %s on ELB %s', policy_name, name) return False except boto.exception.BotoServerError as e: log.error('Failed to create policy %s on ELB %s: %s', policy_name, name, e.message, exc_info_on_loglevel=logging.DEBUG) return False def delete_policy(name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Delete an ELB policy. .. versionadded:: 2016.3.0 CLI example: .. code-block:: bash salt myminion boto_elb.delete_policy myelb mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not exists(name, region, key, keyid, profile): return True try: conn.delete_lb_policy(name, policy_name) log.info('Deleted policy %s on ELB %s', policy_name, name) return True except boto.exception.BotoServerError as e: log.error('Failed to delete policy %s on ELB %s: %s', policy_name, name, e.message, exc_info_on_loglevel=logging.DEBUG) return False def set_listener_policy(name, port, policies=None, region=None, key=None, keyid=None, profile=None): ''' Set the policies of an ELB listener. .. versionadded:: 2016.3.0 CLI example: .. code-block:: Bash salt myminion boto_elb.set_listener_policy myelb 443 "[policy1,policy2]" ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not exists(name, region, key, keyid, profile): return True if policies is None: policies = [] try: conn.set_lb_policies_of_listener(name, port, policies) log.info('Set policies %s on ELB %s listener %s', policies, name, port) except boto.exception.BotoServerError as e: log.info('Failed to set policy %s on ELB %s listener %s: %s', policies, name, port, e.message, exc_info_on_loglevel=logging.DEBUG) return False return True def set_backend_policy(name, port, policies=None, region=None, key=None, keyid=None, profile=None): ''' Set the policies of an ELB backend server. CLI example: salt myminion boto_elb.set_backend_policy myelb 443 "[policy1,policy2]" ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not exists(name, region, key, keyid, profile): return True if policies is None: policies = [] try: conn.set_lb_policies_of_backend_server(name, port, policies) log.info('Set policies %s on ELB %s backend server %s', policies, name, port) except boto.exception.BotoServerError as e: log.info('Failed to set policy %s on ELB %s backend server %s: %s', policies, name, port, e.message, exc_info_on_loglevel=logging.DEBUG) return False return True def set_tags(name, tags, region=None, key=None, keyid=None, profile=None): ''' Add the tags on an ELB .. versionadded:: 2016.3.0 name name of the ELB tags dict of name/value pair tags CLI Example: .. code-block:: bash salt myminion boto_elb.set_tags my-elb-name "{'Tag1': 'Value', 'Tag2': 'Another Value'}" ''' if exists(name, region, key, keyid, profile): conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) ret = _add_tags(conn, name, tags) return ret else: return False def delete_tags(name, tags, region=None, key=None, keyid=None, profile=None): ''' Add the tags on an ELB name name of the ELB tags list of tags to remove CLI Example: .. code-block:: bash salt myminion boto_elb.delete_tags my-elb-name ['TagToRemove1', 'TagToRemove2'] ''' if exists(name, region, key, keyid, profile): conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) ret = _remove_tags(conn, name, tags) return ret else: return False def _build_tag_param_list(params, tags): ''' helper function to build a tag parameter list to send ''' keys = sorted(tags.keys()) i = 1 for key in keys: value = tags[key] params['Tags.member.{0}.Key'.format(i)] = key if value is not None: params['Tags.member.{0}.Value'.format(i)] = value i += 1 def _get_all_tags(conn, load_balancer_names=None): ''' Retrieve all the metadata tags associated with your ELB(s). :type load_balancer_names: list :param load_balancer_names: An optional list of load balancer names. :rtype: list :return: A list of :class:`boto.ec2.elb.tag.Tag` objects ''' params = {} if load_balancer_names: conn.build_list_params(params, load_balancer_names, 'LoadBalancerNames.member.%d') tags = conn.get_object( 'DescribeTags', params, __utils__['boto_elb_tag.get_tag_descriptions'](), verb='POST' ) if tags[load_balancer_names]: return tags[load_balancer_names] else: return None def _add_tags(conn, load_balancer_names, tags): ''' Create new metadata tags for the specified resource ids. :type load_balancer_names: list :param load_balancer_names: A list of load balancer names. :type tags: dict :param tags: A dictionary containing the name/value pairs. If you want to create only a tag name, the value for that tag should be the empty string (e.g. ''). ''' params = {} conn.build_list_params(params, load_balancer_names, 'LoadBalancerNames.member.%d') _build_tag_param_list(params, tags) return conn.get_status('AddTags', params, verb='POST') def _remove_tags(conn, load_balancer_names, tags): ''' Delete metadata tags for the specified resource ids. :type load_balancer_names: list :param load_balancer_names: A list of load balancer names. :type tags: list :param tags: A list containing just tag names for the tags to be deleted. ''' params = {} conn.build_list_params(params, load_balancer_names, 'LoadBalancerNames.member.%d') conn.build_list_params(params, tags, 'Tags.member.%d.Key') return conn.get_status('RemoveTags', params, verb='POST')
saltstack/salt
salt/modules/boto_elb.py
list_elbs
python
def list_elbs(region=None, key=None, keyid=None, profile=None): ''' Return names of all load balancers associated with an account CLI example: .. code-block:: bash salt myminion boto_elb.list_elbs region=us-east-1 ''' return [e.name for e in get_all_elbs(region=region, key=key, keyid=keyid, profile=profile)]
Return names of all load balancers associated with an account CLI example: .. code-block:: bash salt myminion boto_elb.list_elbs region=us-east-1
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_elb.py#L133-L145
[ "def get_all_elbs(region=None, key=None, keyid=None, profile=None):\n '''\n Return all load balancers associated with an account\n\n CLI example:\n\n .. code-block:: bash\n\n salt myminion boto_elb.get_all_elbs region=us-east-1\n '''\n conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)\n\n try:\n return [e for e in conn.get_all_load_balancers()]\n except boto.exception.BotoServerError as error:\n log.warning(error)\n return []\n" ]
# -*- coding: utf-8 -*- ''' Connection module for Amazon ELB .. versionadded:: 2014.7.0 :configuration: This module accepts explicit elb credentials but can also utilize IAM roles assigned to the instance through Instance Profiles. Dynamic credentials are then automatically obtained from AWS API and no further configuration is necessary. More Information available at: .. code-block:: text http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/iam-roles-for-amazon-ec2.html If IAM roles are not used you need to specify them either in a pillar or in the minion's config file: .. code-block:: yaml elb.keyid: GKTADJGHEIQSXMKKRBJ08H elb.key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs A region may also be specified in the configuration: .. code-block:: yaml elb.region: us-east-1 If a region is not specified, the default is us-east-1. It's also possible to specify key, keyid and region via a profile, either as a passed in dict, or as a string to pull from pillars or minion config: .. code-block:: yaml myprofile: keyid: GKTADJGHEIQSXMKKRBJ08H key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs region: us-east-1 :depends: boto >= 2.33.0 ''' # keep lint from choking on _get_conn and _cache_id # pylint: disable=E0602 from __future__ import absolute_import, print_function, unicode_literals # Import Python libs import logging import time log = logging.getLogger(__name__) # Import Salt libs import salt.utils.json import salt.utils.odict as odict import salt.utils.versions # Import third party libs from salt.ext import six try: import boto import boto.ec2 # pylint: enable=unused-import from boto.ec2.elb import HealthCheck from boto.ec2.elb.attributes import AccessLogAttribute from boto.ec2.elb.attributes import ConnectionDrainingAttribute from boto.ec2.elb.attributes import ConnectionSettingAttribute from boto.ec2.elb.attributes import CrossZoneLoadBalancingAttribute logging.getLogger('boto').setLevel(logging.CRITICAL) HAS_BOTO = True except ImportError: HAS_BOTO = False def __virtual__(): ''' Only load if boto libraries exist. ''' # connection settings were added in 2.33.0 has_boto_reqs = salt.utils.versions.check_boto_reqs( boto_ver='2.33.0', check_boto3=False ) if has_boto_reqs is True: __utils__['boto.assign_funcs'](__name__, 'elb', module='ec2.elb', pack=__salt__) return has_boto_reqs def exists(name, region=None, key=None, keyid=None, profile=None): ''' Check to see if an ELB exists. CLI example: .. code-block:: bash salt myminion boto_elb.exists myelb region=us-east-1 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: elb = conn.get_all_load_balancers(load_balancer_names=[name]) if elb: return True else: log.debug('The load balancer does not exist in region %s', region) return False except boto.exception.BotoServerError as error: log.warning(error) return False def get_all_elbs(region=None, key=None, keyid=None, profile=None): ''' Return all load balancers associated with an account CLI example: .. code-block:: bash salt myminion boto_elb.get_all_elbs region=us-east-1 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: return [e for e in conn.get_all_load_balancers()] except boto.exception.BotoServerError as error: log.warning(error) return [] def get_elb_config(name, region=None, key=None, keyid=None, profile=None): ''' Get an ELB configuration. CLI example: .. code-block:: bash salt myminion boto_elb.exists myelb region=us-east-1 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) retries = 30 while retries: try: lb = conn.get_all_load_balancers(load_balancer_names=[name]) lb = lb[0] ret = {} ret['availability_zones'] = lb.availability_zones listeners = [] for _listener in lb.listeners: listener_dict = {} listener_dict['elb_port'] = _listener.load_balancer_port listener_dict['elb_protocol'] = _listener.protocol listener_dict['instance_port'] = _listener.instance_port listener_dict['instance_protocol'] = _listener.instance_protocol listener_dict['policies'] = _listener.policy_names if _listener.ssl_certificate_id: listener_dict['certificate'] = _listener.ssl_certificate_id listeners.append(listener_dict) ret['listeners'] = listeners backends = [] for _backend in lb.backends: bs_dict = {} bs_dict['instance_port'] = _backend.instance_port bs_dict['policies'] = [p.policy_name for p in _backend.policies] backends.append(bs_dict) ret['backends'] = backends ret['subnets'] = lb.subnets ret['security_groups'] = lb.security_groups ret['scheme'] = lb.scheme ret['dns_name'] = lb.dns_name ret['tags'] = _get_all_tags(conn, name) lb_policy_lists = [ lb.policies.app_cookie_stickiness_policies, lb.policies.lb_cookie_stickiness_policies, lb.policies.other_policies ] policies = [] for policy_list in lb_policy_lists: policies += [p.policy_name for p in policy_list] ret['policies'] = policies return ret except boto.exception.BotoServerError as error: if error.error_code == 'Throttling': log.debug('Throttled by AWS API, will retry in 5 seconds.') time.sleep(5) retries -= 1 continue log.error('Error fetching config for ELB %s: %s', name, error.message) log.error(error) return {} return {} def listener_dict_to_tuple(listener): ''' Convert an ELB listener dict into a listener tuple used by certain parts of the AWS ELB API. CLI example: .. code-block:: bash salt myminion boto_elb.listener_dict_to_tuple '{"elb_port":80,"instance_port":80,"elb_protocol":"HTTP"}' ''' # We define all listeners as complex listeners. if 'instance_protocol' not in listener: instance_protocol = listener['elb_protocol'].upper() else: instance_protocol = listener['instance_protocol'].upper() listener_tuple = [listener['elb_port'], listener['instance_port'], listener['elb_protocol'], instance_protocol] if 'certificate' in listener: listener_tuple.append(listener['certificate']) return tuple(listener_tuple) def create(name, availability_zones, listeners, subnets=None, security_groups=None, scheme='internet-facing', region=None, key=None, keyid=None, profile=None): ''' Create an ELB CLI example to create an ELB: .. code-block:: bash salt myminion boto_elb.create myelb '["us-east-1a", "us-east-1e"]' '{"elb_port": 443, "elb_protocol": "HTTPS", ...}' region=us-east-1 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if exists(name, region, key, keyid, profile): return True if isinstance(availability_zones, six.string_types): availability_zones = salt.utils.json.loads(availability_zones) if isinstance(listeners, six.string_types): listeners = salt.utils.json.loads(listeners) _complex_listeners = [] for listener in listeners: _complex_listeners.append(listener_dict_to_tuple(listener)) try: lb = conn.create_load_balancer(name=name, zones=availability_zones, subnets=subnets, security_groups=security_groups, scheme=scheme, complex_listeners=_complex_listeners) if lb: log.info('Created ELB %s', name) return True else: log.error('Failed to create ELB %s', name) return False except boto.exception.BotoServerError as error: log.error('Failed to create ELB %s: %s: %s', name, error.error_code, error.message, exc_info_on_loglevel=logging.DEBUG) return False def delete(name, region=None, key=None, keyid=None, profile=None): ''' Delete an ELB. CLI example to delete an ELB: .. code-block:: bash salt myminion boto_elb.delete myelb region=us-east-1 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not exists(name, region, key, keyid, profile): return True try: conn.delete_load_balancer(name) log.info('Deleted ELB %s.', name) return True except boto.exception.BotoServerError as error: log.error('Failed to delete ELB %s', name, exc_info_on_loglevel=logging.DEBUG) return False def create_listeners(name, listeners, region=None, key=None, keyid=None, profile=None): ''' Create listeners on an ELB. CLI example: .. code-block:: bash salt myminion boto_elb.create_listeners myelb '[["HTTPS", "HTTP", 443, 80, "arn:aws:iam::11 11111:server-certificate/mycert"]]' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if isinstance(listeners, six.string_types): listeners = salt.utils.json.loads(listeners) _complex_listeners = [] for listener in listeners: _complex_listeners.append(listener_dict_to_tuple(listener)) try: conn.create_load_balancer_listeners(name, [], _complex_listeners) log.info('Created ELB listeners on %s', name) return True except boto.exception.BotoServerError as error: log.error('Failed to create ELB listeners on %s: %s', name, error, exc_info_on_loglevel=logging.DEBUG) return False def delete_listeners(name, ports, region=None, key=None, keyid=None, profile=None): ''' Delete listeners on an ELB. CLI example: .. code-block:: bash salt myminion boto_elb.delete_listeners myelb '[80,443]' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if isinstance(ports, six.string_types): ports = salt.utils.json.loads(ports) try: conn.delete_load_balancer_listeners(name, ports) log.info('Deleted ELB listeners on %s', name) return True except boto.exception.BotoServerError as error: log.error('Failed to delete ELB listeners on %s: %s', name, error, exc_info_on_loglevel=logging.DEBUG) return False def apply_security_groups(name, security_groups, region=None, key=None, keyid=None, profile=None): ''' Apply security groups to ELB. CLI example: .. code-block:: bash salt myminion boto_elb.apply_security_groups myelb '["mysecgroup1"]' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if isinstance(security_groups, six.string_types): security_groups = salt.utils.json.loads(security_groups) try: conn.apply_security_groups_to_lb(name, security_groups) log.info('Applied security_groups on ELB %s', name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to appply security_groups on ELB %s: %s', name, e.message) return False def enable_availability_zones(name, availability_zones, region=None, key=None, keyid=None, profile=None): ''' Enable availability zones for ELB. CLI example: .. code-block:: bash salt myminion boto_elb.enable_availability_zones myelb '["us-east-1a"]' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if isinstance(availability_zones, six.string_types): availability_zones = salt.utils.json.loads(availability_zones) try: conn.enable_availability_zones(name, availability_zones) log.info('Enabled availability_zones on ELB %s', name) return True except boto.exception.BotoServerError as error: log.error('Failed to enable availability_zones on ELB %s: %s', name, error) return False def disable_availability_zones(name, availability_zones, region=None, key=None, keyid=None, profile=None): ''' Disable availability zones for ELB. CLI example: .. code-block:: bash salt myminion boto_elb.disable_availability_zones myelb '["us-east-1a"]' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if isinstance(availability_zones, six.string_types): availability_zones = salt.utils.json.loads(availability_zones) try: conn.disable_availability_zones(name, availability_zones) log.info('Disabled availability_zones on ELB %s', name) return True except boto.exception.BotoServerError as error: log.error('Failed to disable availability_zones on ELB %s: %s', name, error, exc_info_on_loglevel=logging.DEBUG) return False def attach_subnets(name, subnets, region=None, key=None, keyid=None, profile=None): ''' Attach ELB to subnets. CLI example: .. code-block:: bash salt myminion boto_elb.attach_subnets myelb '["mysubnet"]' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if isinstance(subnets, six.string_types): subnets = salt.utils.json.loads(subnets) try: conn.attach_lb_to_subnets(name, subnets) log.info('Attached ELB %s on subnets.', name) return True except boto.exception.BotoServerError as error: log.error('Failed to attach ELB %s on subnets: %s', name, error, exc_info_on_loglevel=logging.DEBUG) return False def detach_subnets(name, subnets, region=None, key=None, keyid=None, profile=None): ''' Detach ELB from subnets. CLI example: .. code-block:: bash salt myminion boto_elb.detach_subnets myelb '["mysubnet"]' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if isinstance(subnets, six.string_types): subnets = salt.utils.json.loads(subnets) try: conn.detach_lb_from_subnets(name, subnets) log.info('Detached ELB %s from subnets.', name) return True except boto.exception.BotoServerError as error: log.error('Failed to detach ELB %s from subnets: %s', name, error, exc_info_on_loglevel=logging.DEBUG) return False def get_attributes(name, region=None, key=None, keyid=None, profile=None): ''' Check to see if attributes are set on an ELB. CLI example: .. code-block:: bash salt myminion boto_elb.get_attributes myelb ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) retries = 30 while retries: try: lbattrs = conn.get_all_lb_attributes(name) ret = odict.OrderedDict() ret['access_log'] = odict.OrderedDict() ret['cross_zone_load_balancing'] = odict.OrderedDict() ret['connection_draining'] = odict.OrderedDict() ret['connecting_settings'] = odict.OrderedDict() al = lbattrs.access_log czlb = lbattrs.cross_zone_load_balancing cd = lbattrs.connection_draining cs = lbattrs.connecting_settings ret['access_log']['enabled'] = al.enabled ret['access_log']['s3_bucket_name'] = al.s3_bucket_name ret['access_log']['s3_bucket_prefix'] = al.s3_bucket_prefix ret['access_log']['emit_interval'] = al.emit_interval ret['cross_zone_load_balancing']['enabled'] = czlb.enabled ret['connection_draining']['enabled'] = cd.enabled ret['connection_draining']['timeout'] = cd.timeout ret['connecting_settings']['idle_timeout'] = cs.idle_timeout return ret except boto.exception.BotoServerError as e: if e.error_code == 'Throttling': log.debug("Throttled by AWS API, will retry in 5 seconds...") time.sleep(5) retries -= 1 continue log.error('ELB %s does not exist: %s', name, e.message) return {} return {} def set_attributes(name, attributes, region=None, key=None, keyid=None, profile=None): ''' Set attributes on an ELB. name (string) Name of the ELB instance to set attributes for attributes A dict of attributes to set. Valid attributes are: access_log (dict) enabled (bool) Enable storage of access logs. s3_bucket_name (string) The name of the S3 bucket to place logs. s3_bucket_prefix (string) Prefix for the log file name. emit_interval (int) Interval for storing logs in S3 in minutes. Valid values are 5 and 60. connection_draining (dict) enabled (bool) Enable connection draining. timeout (int) Maximum allowed time in seconds for sending existing connections to an instance that is deregistering or unhealthy. Default is 300. cross_zone_load_balancing (dict) enabled (bool) Enable cross-zone load balancing. CLI example to set attributes on an ELB: .. code-block:: bash salt myminion boto_elb.set_attributes myelb '{"access_log": {"enabled": "true", "s3_bucket_name": "mybucket", "s3_bucket_prefix": "mylogs/", "emit_interval": "5"}}' region=us-east-1 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) al = attributes.get('access_log', {}) czlb = attributes.get('cross_zone_load_balancing', {}) cd = attributes.get('connection_draining', {}) cs = attributes.get('connecting_settings', {}) if not al and not czlb and not cd and not cs: log.error('No supported attributes for ELB.') return False if al: _al = AccessLogAttribute() _al.enabled = al.get('enabled', False) if not _al.enabled: msg = 'Access log attribute configured, but enabled config missing' log.error(msg) return False _al.s3_bucket_name = al.get('s3_bucket_name', None) _al.s3_bucket_prefix = al.get('s3_bucket_prefix', None) _al.emit_interval = al.get('emit_interval', None) added_attr = conn.modify_lb_attribute(name, 'accessLog', _al) if added_attr: log.info('Added access_log attribute to %s elb.', name) else: log.error('Failed to add access_log attribute to %s elb.', name) return False if czlb: _czlb = CrossZoneLoadBalancingAttribute() _czlb.enabled = czlb['enabled'] added_attr = conn.modify_lb_attribute(name, 'crossZoneLoadBalancing', _czlb.enabled) if added_attr: log.info('Added cross_zone_load_balancing attribute to %s elb.', name) else: log.error('Failed to add cross_zone_load_balancing attribute.') return False if cd: _cd = ConnectionDrainingAttribute() _cd.enabled = cd['enabled'] _cd.timeout = cd.get('timeout', 300) added_attr = conn.modify_lb_attribute(name, 'connectionDraining', _cd) if added_attr: log.info('Added connection_draining attribute to %s elb.', name) else: log.error('Failed to add connection_draining attribute.') return False if cs: _cs = ConnectionSettingAttribute() _cs.idle_timeout = cs.get('idle_timeout', 60) added_attr = conn.modify_lb_attribute(name, 'connectingSettings', _cs) if added_attr: log.info('Added connecting_settings attribute to %s elb.', name) else: log.error('Failed to add connecting_settings attribute.') return False return True def get_health_check(name, region=None, key=None, keyid=None, profile=None): ''' Get the health check configured for this ELB. CLI example: .. code-block:: bash salt myminion boto_elb.get_health_check myelb ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) retries = 30 while True: try: lb = conn.get_all_load_balancers(load_balancer_names=[name]) lb = lb[0] ret = odict.OrderedDict() hc = lb.health_check ret['interval'] = hc.interval ret['target'] = hc.target ret['healthy_threshold'] = hc.healthy_threshold ret['timeout'] = hc.timeout ret['unhealthy_threshold'] = hc.unhealthy_threshold return ret except boto.exception.BotoServerError as e: if retries and e.code == 'Throttling': log.debug('Throttled by AWS API, will retry in 5 seconds.') time.sleep(5) retries -= 1 continue log.error('ELB %s not found.', name, exc_info_on_logleve=logging.DEBUG) return {} def set_health_check(name, health_check, region=None, key=None, keyid=None, profile=None): ''' Set attributes on an ELB. CLI example to set attributes on an ELB: .. code-block:: bash salt myminion boto_elb.set_health_check myelb '{"target": "HTTP:80/"}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) retries = 30 hc = HealthCheck(**health_check) while True: try: conn.configure_health_check(name, hc) log.info('Configured health check on ELB %s', name) return True except boto.exception.BotoServerError as error: if retries and e.code == 'Throttling': log.debug('Throttled by AWS API, will retry in 5 seconds.') time.sleep(5) retries -= 1 continue log.exception('Failed to configure health check on ELB %s', name) return False def register_instances(name, instances, region=None, key=None, keyid=None, profile=None): ''' Register instances with an ELB. Instances is either a string instance id or a list of string instance id's. Returns: - ``True``: instance(s) registered successfully - ``False``: instance(s) failed to be registered CLI example: .. code-block:: bash salt myminion boto_elb.register_instances myelb instance_id salt myminion boto_elb.register_instances myelb "[instance_id,instance_id]" ''' # convert instances to list type, enabling consistent use of instances # variable throughout the register_instances method if isinstance(instances, six.string_types) or isinstance(instances, six.text_type): instances = [instances] conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: registered_instances = conn.register_instances(name, instances) except boto.exception.BotoServerError as error: log.warning(error) return False registered_instance_ids = [instance.id for instance in registered_instances] # register_failues is a set that will contain any instances that were not # able to be registered with the given ELB register_failures = set(instances).difference(set(registered_instance_ids)) if register_failures: log.warning('Instance(s): %s not registered with ELB %s.', list(register_failures), name) register_result = False else: register_result = True return register_result def deregister_instances(name, instances, region=None, key=None, keyid=None, profile=None): ''' Deregister instances with an ELB. Instances is either a string instance id or a list of string instance id's. Returns: - ``True``: instance(s) deregistered successfully - ``False``: instance(s) failed to be deregistered - ``None``: instance(s) not valid or not registered, no action taken CLI example: .. code-block:: bash salt myminion boto_elb.deregister_instances myelb instance_id salt myminion boto_elb.deregister_instances myelb "[instance_id, instance_id]" ''' # convert instances to list type, enabling consistent use of instances # variable throughout the deregister_instances method if isinstance(instances, six.string_types) or isinstance(instances, six.text_type): instances = [instances] conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: registered_instances = conn.deregister_instances(name, instances) except boto.exception.BotoServerError as error: # if the instance(s) given as an argument are not members of the ELB # boto returns error.error_code == 'InvalidInstance' # deregister_instances returns "None" because the instances are # effectively deregistered from ELB if error.error_code == 'InvalidInstance': log.warning( 'One or more of instance(s) %s are not part of ELB %s. ' 'deregister_instances not performed.', instances, name ) return None else: log.warning(error) return False registered_instance_ids = [instance.id for instance in registered_instances] # deregister_failures is a set that will contain any instances that were # unable to be deregistered from the given ELB deregister_failures = set(instances).intersection(set(registered_instance_ids)) if deregister_failures: log.warning( 'Instance(s): %s not deregistered from ELB %s.', list(deregister_failures), name ) deregister_result = False else: deregister_result = True return deregister_result def set_instances(name, instances, test=False, region=None, key=None, keyid=None, profile=None): ''' Set the instances assigned to an ELB to exactly the list given CLI example: .. code-block:: bash salt myminion boto_elb.set_instances myelb region=us-east-1 instances="[instance_id,instance_id]" ''' ret = True current = set([i['instance_id'] for i in get_instance_health(name, region, key, keyid, profile)]) desired = set(instances) add = desired - current remove = current - desired if test: return bool(add or remove) if remove: if deregister_instances(name, list(remove), region, key, keyid, profile) is False: ret = False if add: if register_instances(name, list(add), region, key, keyid, profile) is False: ret = False return ret def get_instance_health(name, region=None, key=None, keyid=None, profile=None, instances=None): ''' Get a list of instances and their health state CLI example: .. code-block:: bash salt myminion boto_elb.get_instance_health myelb salt myminion boto_elb.get_instance_health myelb region=us-east-1 instances="[instance_id,instance_id]" ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: instance_states = conn.describe_instance_health(name, instances) ret = [] for _instance in instance_states: ret.append({'instance_id': _instance.instance_id, 'description': _instance.description, 'state': _instance.state, 'reason_code': _instance.reason_code }) return ret except boto.exception.BotoServerError as error: log.debug(error) return [] def create_policy(name, policy_name, policy_type, policy, region=None, key=None, keyid=None, profile=None): ''' Create an ELB policy. .. versionadded:: 2016.3.0 CLI example: .. code-block:: bash salt myminion boto_elb.create_policy myelb mypolicy LBCookieStickinessPolicyType '{"CookieExpirationPeriod": 3600}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not exists(name, region, key, keyid, profile): return False try: success = conn.create_lb_policy(name, policy_name, policy_type, policy) if success: log.info('Created policy %s on ELB %s', policy_name, name) return True else: log.error('Failed to create policy %s on ELB %s', policy_name, name) return False except boto.exception.BotoServerError as e: log.error('Failed to create policy %s on ELB %s: %s', policy_name, name, e.message, exc_info_on_loglevel=logging.DEBUG) return False def delete_policy(name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Delete an ELB policy. .. versionadded:: 2016.3.0 CLI example: .. code-block:: bash salt myminion boto_elb.delete_policy myelb mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not exists(name, region, key, keyid, profile): return True try: conn.delete_lb_policy(name, policy_name) log.info('Deleted policy %s on ELB %s', policy_name, name) return True except boto.exception.BotoServerError as e: log.error('Failed to delete policy %s on ELB %s: %s', policy_name, name, e.message, exc_info_on_loglevel=logging.DEBUG) return False def set_listener_policy(name, port, policies=None, region=None, key=None, keyid=None, profile=None): ''' Set the policies of an ELB listener. .. versionadded:: 2016.3.0 CLI example: .. code-block:: Bash salt myminion boto_elb.set_listener_policy myelb 443 "[policy1,policy2]" ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not exists(name, region, key, keyid, profile): return True if policies is None: policies = [] try: conn.set_lb_policies_of_listener(name, port, policies) log.info('Set policies %s on ELB %s listener %s', policies, name, port) except boto.exception.BotoServerError as e: log.info('Failed to set policy %s on ELB %s listener %s: %s', policies, name, port, e.message, exc_info_on_loglevel=logging.DEBUG) return False return True def set_backend_policy(name, port, policies=None, region=None, key=None, keyid=None, profile=None): ''' Set the policies of an ELB backend server. CLI example: salt myminion boto_elb.set_backend_policy myelb 443 "[policy1,policy2]" ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not exists(name, region, key, keyid, profile): return True if policies is None: policies = [] try: conn.set_lb_policies_of_backend_server(name, port, policies) log.info('Set policies %s on ELB %s backend server %s', policies, name, port) except boto.exception.BotoServerError as e: log.info('Failed to set policy %s on ELB %s backend server %s: %s', policies, name, port, e.message, exc_info_on_loglevel=logging.DEBUG) return False return True def set_tags(name, tags, region=None, key=None, keyid=None, profile=None): ''' Add the tags on an ELB .. versionadded:: 2016.3.0 name name of the ELB tags dict of name/value pair tags CLI Example: .. code-block:: bash salt myminion boto_elb.set_tags my-elb-name "{'Tag1': 'Value', 'Tag2': 'Another Value'}" ''' if exists(name, region, key, keyid, profile): conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) ret = _add_tags(conn, name, tags) return ret else: return False def delete_tags(name, tags, region=None, key=None, keyid=None, profile=None): ''' Add the tags on an ELB name name of the ELB tags list of tags to remove CLI Example: .. code-block:: bash salt myminion boto_elb.delete_tags my-elb-name ['TagToRemove1', 'TagToRemove2'] ''' if exists(name, region, key, keyid, profile): conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) ret = _remove_tags(conn, name, tags) return ret else: return False def _build_tag_param_list(params, tags): ''' helper function to build a tag parameter list to send ''' keys = sorted(tags.keys()) i = 1 for key in keys: value = tags[key] params['Tags.member.{0}.Key'.format(i)] = key if value is not None: params['Tags.member.{0}.Value'.format(i)] = value i += 1 def _get_all_tags(conn, load_balancer_names=None): ''' Retrieve all the metadata tags associated with your ELB(s). :type load_balancer_names: list :param load_balancer_names: An optional list of load balancer names. :rtype: list :return: A list of :class:`boto.ec2.elb.tag.Tag` objects ''' params = {} if load_balancer_names: conn.build_list_params(params, load_balancer_names, 'LoadBalancerNames.member.%d') tags = conn.get_object( 'DescribeTags', params, __utils__['boto_elb_tag.get_tag_descriptions'](), verb='POST' ) if tags[load_balancer_names]: return tags[load_balancer_names] else: return None def _add_tags(conn, load_balancer_names, tags): ''' Create new metadata tags for the specified resource ids. :type load_balancer_names: list :param load_balancer_names: A list of load balancer names. :type tags: dict :param tags: A dictionary containing the name/value pairs. If you want to create only a tag name, the value for that tag should be the empty string (e.g. ''). ''' params = {} conn.build_list_params(params, load_balancer_names, 'LoadBalancerNames.member.%d') _build_tag_param_list(params, tags) return conn.get_status('AddTags', params, verb='POST') def _remove_tags(conn, load_balancer_names, tags): ''' Delete metadata tags for the specified resource ids. :type load_balancer_names: list :param load_balancer_names: A list of load balancer names. :type tags: list :param tags: A list containing just tag names for the tags to be deleted. ''' params = {} conn.build_list_params(params, load_balancer_names, 'LoadBalancerNames.member.%d') conn.build_list_params(params, tags, 'Tags.member.%d.Key') return conn.get_status('RemoveTags', params, verb='POST')
saltstack/salt
salt/modules/boto_elb.py
get_elb_config
python
def get_elb_config(name, region=None, key=None, keyid=None, profile=None): ''' Get an ELB configuration. CLI example: .. code-block:: bash salt myminion boto_elb.exists myelb region=us-east-1 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) retries = 30 while retries: try: lb = conn.get_all_load_balancers(load_balancer_names=[name]) lb = lb[0] ret = {} ret['availability_zones'] = lb.availability_zones listeners = [] for _listener in lb.listeners: listener_dict = {} listener_dict['elb_port'] = _listener.load_balancer_port listener_dict['elb_protocol'] = _listener.protocol listener_dict['instance_port'] = _listener.instance_port listener_dict['instance_protocol'] = _listener.instance_protocol listener_dict['policies'] = _listener.policy_names if _listener.ssl_certificate_id: listener_dict['certificate'] = _listener.ssl_certificate_id listeners.append(listener_dict) ret['listeners'] = listeners backends = [] for _backend in lb.backends: bs_dict = {} bs_dict['instance_port'] = _backend.instance_port bs_dict['policies'] = [p.policy_name for p in _backend.policies] backends.append(bs_dict) ret['backends'] = backends ret['subnets'] = lb.subnets ret['security_groups'] = lb.security_groups ret['scheme'] = lb.scheme ret['dns_name'] = lb.dns_name ret['tags'] = _get_all_tags(conn, name) lb_policy_lists = [ lb.policies.app_cookie_stickiness_policies, lb.policies.lb_cookie_stickiness_policies, lb.policies.other_policies ] policies = [] for policy_list in lb_policy_lists: policies += [p.policy_name for p in policy_list] ret['policies'] = policies return ret except boto.exception.BotoServerError as error: if error.error_code == 'Throttling': log.debug('Throttled by AWS API, will retry in 5 seconds.') time.sleep(5) retries -= 1 continue log.error('Error fetching config for ELB %s: %s', name, error.message) log.error(error) return {} return {}
Get an ELB configuration. CLI example: .. code-block:: bash salt myminion boto_elb.exists myelb region=us-east-1
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_elb.py#L148-L210
[ "def _get_all_tags(conn, load_balancer_names=None):\n '''\n Retrieve all the metadata tags associated with your ELB(s).\n\n :type load_balancer_names: list\n :param load_balancer_names: An optional list of load balancer names.\n\n :rtype: list\n :return: A list of :class:`boto.ec2.elb.tag.Tag` objects\n '''\n params = {}\n if load_balancer_names:\n conn.build_list_params(params, load_balancer_names,\n 'LoadBalancerNames.member.%d')\n\n tags = conn.get_object(\n 'DescribeTags',\n params,\n __utils__['boto_elb_tag.get_tag_descriptions'](),\n verb='POST'\n )\n if tags[load_balancer_names]:\n return tags[load_balancer_names]\n else:\n return None\n" ]
# -*- coding: utf-8 -*- ''' Connection module for Amazon ELB .. versionadded:: 2014.7.0 :configuration: This module accepts explicit elb credentials but can also utilize IAM roles assigned to the instance through Instance Profiles. Dynamic credentials are then automatically obtained from AWS API and no further configuration is necessary. More Information available at: .. code-block:: text http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/iam-roles-for-amazon-ec2.html If IAM roles are not used you need to specify them either in a pillar or in the minion's config file: .. code-block:: yaml elb.keyid: GKTADJGHEIQSXMKKRBJ08H elb.key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs A region may also be specified in the configuration: .. code-block:: yaml elb.region: us-east-1 If a region is not specified, the default is us-east-1. It's also possible to specify key, keyid and region via a profile, either as a passed in dict, or as a string to pull from pillars or minion config: .. code-block:: yaml myprofile: keyid: GKTADJGHEIQSXMKKRBJ08H key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs region: us-east-1 :depends: boto >= 2.33.0 ''' # keep lint from choking on _get_conn and _cache_id # pylint: disable=E0602 from __future__ import absolute_import, print_function, unicode_literals # Import Python libs import logging import time log = logging.getLogger(__name__) # Import Salt libs import salt.utils.json import salt.utils.odict as odict import salt.utils.versions # Import third party libs from salt.ext import six try: import boto import boto.ec2 # pylint: enable=unused-import from boto.ec2.elb import HealthCheck from boto.ec2.elb.attributes import AccessLogAttribute from boto.ec2.elb.attributes import ConnectionDrainingAttribute from boto.ec2.elb.attributes import ConnectionSettingAttribute from boto.ec2.elb.attributes import CrossZoneLoadBalancingAttribute logging.getLogger('boto').setLevel(logging.CRITICAL) HAS_BOTO = True except ImportError: HAS_BOTO = False def __virtual__(): ''' Only load if boto libraries exist. ''' # connection settings were added in 2.33.0 has_boto_reqs = salt.utils.versions.check_boto_reqs( boto_ver='2.33.0', check_boto3=False ) if has_boto_reqs is True: __utils__['boto.assign_funcs'](__name__, 'elb', module='ec2.elb', pack=__salt__) return has_boto_reqs def exists(name, region=None, key=None, keyid=None, profile=None): ''' Check to see if an ELB exists. CLI example: .. code-block:: bash salt myminion boto_elb.exists myelb region=us-east-1 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: elb = conn.get_all_load_balancers(load_balancer_names=[name]) if elb: return True else: log.debug('The load balancer does not exist in region %s', region) return False except boto.exception.BotoServerError as error: log.warning(error) return False def get_all_elbs(region=None, key=None, keyid=None, profile=None): ''' Return all load balancers associated with an account CLI example: .. code-block:: bash salt myminion boto_elb.get_all_elbs region=us-east-1 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: return [e for e in conn.get_all_load_balancers()] except boto.exception.BotoServerError as error: log.warning(error) return [] def list_elbs(region=None, key=None, keyid=None, profile=None): ''' Return names of all load balancers associated with an account CLI example: .. code-block:: bash salt myminion boto_elb.list_elbs region=us-east-1 ''' return [e.name for e in get_all_elbs(region=region, key=key, keyid=keyid, profile=profile)] def listener_dict_to_tuple(listener): ''' Convert an ELB listener dict into a listener tuple used by certain parts of the AWS ELB API. CLI example: .. code-block:: bash salt myminion boto_elb.listener_dict_to_tuple '{"elb_port":80,"instance_port":80,"elb_protocol":"HTTP"}' ''' # We define all listeners as complex listeners. if 'instance_protocol' not in listener: instance_protocol = listener['elb_protocol'].upper() else: instance_protocol = listener['instance_protocol'].upper() listener_tuple = [listener['elb_port'], listener['instance_port'], listener['elb_protocol'], instance_protocol] if 'certificate' in listener: listener_tuple.append(listener['certificate']) return tuple(listener_tuple) def create(name, availability_zones, listeners, subnets=None, security_groups=None, scheme='internet-facing', region=None, key=None, keyid=None, profile=None): ''' Create an ELB CLI example to create an ELB: .. code-block:: bash salt myminion boto_elb.create myelb '["us-east-1a", "us-east-1e"]' '{"elb_port": 443, "elb_protocol": "HTTPS", ...}' region=us-east-1 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if exists(name, region, key, keyid, profile): return True if isinstance(availability_zones, six.string_types): availability_zones = salt.utils.json.loads(availability_zones) if isinstance(listeners, six.string_types): listeners = salt.utils.json.loads(listeners) _complex_listeners = [] for listener in listeners: _complex_listeners.append(listener_dict_to_tuple(listener)) try: lb = conn.create_load_balancer(name=name, zones=availability_zones, subnets=subnets, security_groups=security_groups, scheme=scheme, complex_listeners=_complex_listeners) if lb: log.info('Created ELB %s', name) return True else: log.error('Failed to create ELB %s', name) return False except boto.exception.BotoServerError as error: log.error('Failed to create ELB %s: %s: %s', name, error.error_code, error.message, exc_info_on_loglevel=logging.DEBUG) return False def delete(name, region=None, key=None, keyid=None, profile=None): ''' Delete an ELB. CLI example to delete an ELB: .. code-block:: bash salt myminion boto_elb.delete myelb region=us-east-1 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not exists(name, region, key, keyid, profile): return True try: conn.delete_load_balancer(name) log.info('Deleted ELB %s.', name) return True except boto.exception.BotoServerError as error: log.error('Failed to delete ELB %s', name, exc_info_on_loglevel=logging.DEBUG) return False def create_listeners(name, listeners, region=None, key=None, keyid=None, profile=None): ''' Create listeners on an ELB. CLI example: .. code-block:: bash salt myminion boto_elb.create_listeners myelb '[["HTTPS", "HTTP", 443, 80, "arn:aws:iam::11 11111:server-certificate/mycert"]]' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if isinstance(listeners, six.string_types): listeners = salt.utils.json.loads(listeners) _complex_listeners = [] for listener in listeners: _complex_listeners.append(listener_dict_to_tuple(listener)) try: conn.create_load_balancer_listeners(name, [], _complex_listeners) log.info('Created ELB listeners on %s', name) return True except boto.exception.BotoServerError as error: log.error('Failed to create ELB listeners on %s: %s', name, error, exc_info_on_loglevel=logging.DEBUG) return False def delete_listeners(name, ports, region=None, key=None, keyid=None, profile=None): ''' Delete listeners on an ELB. CLI example: .. code-block:: bash salt myminion boto_elb.delete_listeners myelb '[80,443]' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if isinstance(ports, six.string_types): ports = salt.utils.json.loads(ports) try: conn.delete_load_balancer_listeners(name, ports) log.info('Deleted ELB listeners on %s', name) return True except boto.exception.BotoServerError as error: log.error('Failed to delete ELB listeners on %s: %s', name, error, exc_info_on_loglevel=logging.DEBUG) return False def apply_security_groups(name, security_groups, region=None, key=None, keyid=None, profile=None): ''' Apply security groups to ELB. CLI example: .. code-block:: bash salt myminion boto_elb.apply_security_groups myelb '["mysecgroup1"]' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if isinstance(security_groups, six.string_types): security_groups = salt.utils.json.loads(security_groups) try: conn.apply_security_groups_to_lb(name, security_groups) log.info('Applied security_groups on ELB %s', name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to appply security_groups on ELB %s: %s', name, e.message) return False def enable_availability_zones(name, availability_zones, region=None, key=None, keyid=None, profile=None): ''' Enable availability zones for ELB. CLI example: .. code-block:: bash salt myminion boto_elb.enable_availability_zones myelb '["us-east-1a"]' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if isinstance(availability_zones, six.string_types): availability_zones = salt.utils.json.loads(availability_zones) try: conn.enable_availability_zones(name, availability_zones) log.info('Enabled availability_zones on ELB %s', name) return True except boto.exception.BotoServerError as error: log.error('Failed to enable availability_zones on ELB %s: %s', name, error) return False def disable_availability_zones(name, availability_zones, region=None, key=None, keyid=None, profile=None): ''' Disable availability zones for ELB. CLI example: .. code-block:: bash salt myminion boto_elb.disable_availability_zones myelb '["us-east-1a"]' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if isinstance(availability_zones, six.string_types): availability_zones = salt.utils.json.loads(availability_zones) try: conn.disable_availability_zones(name, availability_zones) log.info('Disabled availability_zones on ELB %s', name) return True except boto.exception.BotoServerError as error: log.error('Failed to disable availability_zones on ELB %s: %s', name, error, exc_info_on_loglevel=logging.DEBUG) return False def attach_subnets(name, subnets, region=None, key=None, keyid=None, profile=None): ''' Attach ELB to subnets. CLI example: .. code-block:: bash salt myminion boto_elb.attach_subnets myelb '["mysubnet"]' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if isinstance(subnets, six.string_types): subnets = salt.utils.json.loads(subnets) try: conn.attach_lb_to_subnets(name, subnets) log.info('Attached ELB %s on subnets.', name) return True except boto.exception.BotoServerError as error: log.error('Failed to attach ELB %s on subnets: %s', name, error, exc_info_on_loglevel=logging.DEBUG) return False def detach_subnets(name, subnets, region=None, key=None, keyid=None, profile=None): ''' Detach ELB from subnets. CLI example: .. code-block:: bash salt myminion boto_elb.detach_subnets myelb '["mysubnet"]' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if isinstance(subnets, six.string_types): subnets = salt.utils.json.loads(subnets) try: conn.detach_lb_from_subnets(name, subnets) log.info('Detached ELB %s from subnets.', name) return True except boto.exception.BotoServerError as error: log.error('Failed to detach ELB %s from subnets: %s', name, error, exc_info_on_loglevel=logging.DEBUG) return False def get_attributes(name, region=None, key=None, keyid=None, profile=None): ''' Check to see if attributes are set on an ELB. CLI example: .. code-block:: bash salt myminion boto_elb.get_attributes myelb ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) retries = 30 while retries: try: lbattrs = conn.get_all_lb_attributes(name) ret = odict.OrderedDict() ret['access_log'] = odict.OrderedDict() ret['cross_zone_load_balancing'] = odict.OrderedDict() ret['connection_draining'] = odict.OrderedDict() ret['connecting_settings'] = odict.OrderedDict() al = lbattrs.access_log czlb = lbattrs.cross_zone_load_balancing cd = lbattrs.connection_draining cs = lbattrs.connecting_settings ret['access_log']['enabled'] = al.enabled ret['access_log']['s3_bucket_name'] = al.s3_bucket_name ret['access_log']['s3_bucket_prefix'] = al.s3_bucket_prefix ret['access_log']['emit_interval'] = al.emit_interval ret['cross_zone_load_balancing']['enabled'] = czlb.enabled ret['connection_draining']['enabled'] = cd.enabled ret['connection_draining']['timeout'] = cd.timeout ret['connecting_settings']['idle_timeout'] = cs.idle_timeout return ret except boto.exception.BotoServerError as e: if e.error_code == 'Throttling': log.debug("Throttled by AWS API, will retry in 5 seconds...") time.sleep(5) retries -= 1 continue log.error('ELB %s does not exist: %s', name, e.message) return {} return {} def set_attributes(name, attributes, region=None, key=None, keyid=None, profile=None): ''' Set attributes on an ELB. name (string) Name of the ELB instance to set attributes for attributes A dict of attributes to set. Valid attributes are: access_log (dict) enabled (bool) Enable storage of access logs. s3_bucket_name (string) The name of the S3 bucket to place logs. s3_bucket_prefix (string) Prefix for the log file name. emit_interval (int) Interval for storing logs in S3 in minutes. Valid values are 5 and 60. connection_draining (dict) enabled (bool) Enable connection draining. timeout (int) Maximum allowed time in seconds for sending existing connections to an instance that is deregistering or unhealthy. Default is 300. cross_zone_load_balancing (dict) enabled (bool) Enable cross-zone load balancing. CLI example to set attributes on an ELB: .. code-block:: bash salt myminion boto_elb.set_attributes myelb '{"access_log": {"enabled": "true", "s3_bucket_name": "mybucket", "s3_bucket_prefix": "mylogs/", "emit_interval": "5"}}' region=us-east-1 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) al = attributes.get('access_log', {}) czlb = attributes.get('cross_zone_load_balancing', {}) cd = attributes.get('connection_draining', {}) cs = attributes.get('connecting_settings', {}) if not al and not czlb and not cd and not cs: log.error('No supported attributes for ELB.') return False if al: _al = AccessLogAttribute() _al.enabled = al.get('enabled', False) if not _al.enabled: msg = 'Access log attribute configured, but enabled config missing' log.error(msg) return False _al.s3_bucket_name = al.get('s3_bucket_name', None) _al.s3_bucket_prefix = al.get('s3_bucket_prefix', None) _al.emit_interval = al.get('emit_interval', None) added_attr = conn.modify_lb_attribute(name, 'accessLog', _al) if added_attr: log.info('Added access_log attribute to %s elb.', name) else: log.error('Failed to add access_log attribute to %s elb.', name) return False if czlb: _czlb = CrossZoneLoadBalancingAttribute() _czlb.enabled = czlb['enabled'] added_attr = conn.modify_lb_attribute(name, 'crossZoneLoadBalancing', _czlb.enabled) if added_attr: log.info('Added cross_zone_load_balancing attribute to %s elb.', name) else: log.error('Failed to add cross_zone_load_balancing attribute.') return False if cd: _cd = ConnectionDrainingAttribute() _cd.enabled = cd['enabled'] _cd.timeout = cd.get('timeout', 300) added_attr = conn.modify_lb_attribute(name, 'connectionDraining', _cd) if added_attr: log.info('Added connection_draining attribute to %s elb.', name) else: log.error('Failed to add connection_draining attribute.') return False if cs: _cs = ConnectionSettingAttribute() _cs.idle_timeout = cs.get('idle_timeout', 60) added_attr = conn.modify_lb_attribute(name, 'connectingSettings', _cs) if added_attr: log.info('Added connecting_settings attribute to %s elb.', name) else: log.error('Failed to add connecting_settings attribute.') return False return True def get_health_check(name, region=None, key=None, keyid=None, profile=None): ''' Get the health check configured for this ELB. CLI example: .. code-block:: bash salt myminion boto_elb.get_health_check myelb ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) retries = 30 while True: try: lb = conn.get_all_load_balancers(load_balancer_names=[name]) lb = lb[0] ret = odict.OrderedDict() hc = lb.health_check ret['interval'] = hc.interval ret['target'] = hc.target ret['healthy_threshold'] = hc.healthy_threshold ret['timeout'] = hc.timeout ret['unhealthy_threshold'] = hc.unhealthy_threshold return ret except boto.exception.BotoServerError as e: if retries and e.code == 'Throttling': log.debug('Throttled by AWS API, will retry in 5 seconds.') time.sleep(5) retries -= 1 continue log.error('ELB %s not found.', name, exc_info_on_logleve=logging.DEBUG) return {} def set_health_check(name, health_check, region=None, key=None, keyid=None, profile=None): ''' Set attributes on an ELB. CLI example to set attributes on an ELB: .. code-block:: bash salt myminion boto_elb.set_health_check myelb '{"target": "HTTP:80/"}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) retries = 30 hc = HealthCheck(**health_check) while True: try: conn.configure_health_check(name, hc) log.info('Configured health check on ELB %s', name) return True except boto.exception.BotoServerError as error: if retries and e.code == 'Throttling': log.debug('Throttled by AWS API, will retry in 5 seconds.') time.sleep(5) retries -= 1 continue log.exception('Failed to configure health check on ELB %s', name) return False def register_instances(name, instances, region=None, key=None, keyid=None, profile=None): ''' Register instances with an ELB. Instances is either a string instance id or a list of string instance id's. Returns: - ``True``: instance(s) registered successfully - ``False``: instance(s) failed to be registered CLI example: .. code-block:: bash salt myminion boto_elb.register_instances myelb instance_id salt myminion boto_elb.register_instances myelb "[instance_id,instance_id]" ''' # convert instances to list type, enabling consistent use of instances # variable throughout the register_instances method if isinstance(instances, six.string_types) or isinstance(instances, six.text_type): instances = [instances] conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: registered_instances = conn.register_instances(name, instances) except boto.exception.BotoServerError as error: log.warning(error) return False registered_instance_ids = [instance.id for instance in registered_instances] # register_failues is a set that will contain any instances that were not # able to be registered with the given ELB register_failures = set(instances).difference(set(registered_instance_ids)) if register_failures: log.warning('Instance(s): %s not registered with ELB %s.', list(register_failures), name) register_result = False else: register_result = True return register_result def deregister_instances(name, instances, region=None, key=None, keyid=None, profile=None): ''' Deregister instances with an ELB. Instances is either a string instance id or a list of string instance id's. Returns: - ``True``: instance(s) deregistered successfully - ``False``: instance(s) failed to be deregistered - ``None``: instance(s) not valid or not registered, no action taken CLI example: .. code-block:: bash salt myminion boto_elb.deregister_instances myelb instance_id salt myminion boto_elb.deregister_instances myelb "[instance_id, instance_id]" ''' # convert instances to list type, enabling consistent use of instances # variable throughout the deregister_instances method if isinstance(instances, six.string_types) or isinstance(instances, six.text_type): instances = [instances] conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: registered_instances = conn.deregister_instances(name, instances) except boto.exception.BotoServerError as error: # if the instance(s) given as an argument are not members of the ELB # boto returns error.error_code == 'InvalidInstance' # deregister_instances returns "None" because the instances are # effectively deregistered from ELB if error.error_code == 'InvalidInstance': log.warning( 'One or more of instance(s) %s are not part of ELB %s. ' 'deregister_instances not performed.', instances, name ) return None else: log.warning(error) return False registered_instance_ids = [instance.id for instance in registered_instances] # deregister_failures is a set that will contain any instances that were # unable to be deregistered from the given ELB deregister_failures = set(instances).intersection(set(registered_instance_ids)) if deregister_failures: log.warning( 'Instance(s): %s not deregistered from ELB %s.', list(deregister_failures), name ) deregister_result = False else: deregister_result = True return deregister_result def set_instances(name, instances, test=False, region=None, key=None, keyid=None, profile=None): ''' Set the instances assigned to an ELB to exactly the list given CLI example: .. code-block:: bash salt myminion boto_elb.set_instances myelb region=us-east-1 instances="[instance_id,instance_id]" ''' ret = True current = set([i['instance_id'] for i in get_instance_health(name, region, key, keyid, profile)]) desired = set(instances) add = desired - current remove = current - desired if test: return bool(add or remove) if remove: if deregister_instances(name, list(remove), region, key, keyid, profile) is False: ret = False if add: if register_instances(name, list(add), region, key, keyid, profile) is False: ret = False return ret def get_instance_health(name, region=None, key=None, keyid=None, profile=None, instances=None): ''' Get a list of instances and their health state CLI example: .. code-block:: bash salt myminion boto_elb.get_instance_health myelb salt myminion boto_elb.get_instance_health myelb region=us-east-1 instances="[instance_id,instance_id]" ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: instance_states = conn.describe_instance_health(name, instances) ret = [] for _instance in instance_states: ret.append({'instance_id': _instance.instance_id, 'description': _instance.description, 'state': _instance.state, 'reason_code': _instance.reason_code }) return ret except boto.exception.BotoServerError as error: log.debug(error) return [] def create_policy(name, policy_name, policy_type, policy, region=None, key=None, keyid=None, profile=None): ''' Create an ELB policy. .. versionadded:: 2016.3.0 CLI example: .. code-block:: bash salt myminion boto_elb.create_policy myelb mypolicy LBCookieStickinessPolicyType '{"CookieExpirationPeriod": 3600}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not exists(name, region, key, keyid, profile): return False try: success = conn.create_lb_policy(name, policy_name, policy_type, policy) if success: log.info('Created policy %s on ELB %s', policy_name, name) return True else: log.error('Failed to create policy %s on ELB %s', policy_name, name) return False except boto.exception.BotoServerError as e: log.error('Failed to create policy %s on ELB %s: %s', policy_name, name, e.message, exc_info_on_loglevel=logging.DEBUG) return False def delete_policy(name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Delete an ELB policy. .. versionadded:: 2016.3.0 CLI example: .. code-block:: bash salt myminion boto_elb.delete_policy myelb mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not exists(name, region, key, keyid, profile): return True try: conn.delete_lb_policy(name, policy_name) log.info('Deleted policy %s on ELB %s', policy_name, name) return True except boto.exception.BotoServerError as e: log.error('Failed to delete policy %s on ELB %s: %s', policy_name, name, e.message, exc_info_on_loglevel=logging.DEBUG) return False def set_listener_policy(name, port, policies=None, region=None, key=None, keyid=None, profile=None): ''' Set the policies of an ELB listener. .. versionadded:: 2016.3.0 CLI example: .. code-block:: Bash salt myminion boto_elb.set_listener_policy myelb 443 "[policy1,policy2]" ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not exists(name, region, key, keyid, profile): return True if policies is None: policies = [] try: conn.set_lb_policies_of_listener(name, port, policies) log.info('Set policies %s on ELB %s listener %s', policies, name, port) except boto.exception.BotoServerError as e: log.info('Failed to set policy %s on ELB %s listener %s: %s', policies, name, port, e.message, exc_info_on_loglevel=logging.DEBUG) return False return True def set_backend_policy(name, port, policies=None, region=None, key=None, keyid=None, profile=None): ''' Set the policies of an ELB backend server. CLI example: salt myminion boto_elb.set_backend_policy myelb 443 "[policy1,policy2]" ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not exists(name, region, key, keyid, profile): return True if policies is None: policies = [] try: conn.set_lb_policies_of_backend_server(name, port, policies) log.info('Set policies %s on ELB %s backend server %s', policies, name, port) except boto.exception.BotoServerError as e: log.info('Failed to set policy %s on ELB %s backend server %s: %s', policies, name, port, e.message, exc_info_on_loglevel=logging.DEBUG) return False return True def set_tags(name, tags, region=None, key=None, keyid=None, profile=None): ''' Add the tags on an ELB .. versionadded:: 2016.3.0 name name of the ELB tags dict of name/value pair tags CLI Example: .. code-block:: bash salt myminion boto_elb.set_tags my-elb-name "{'Tag1': 'Value', 'Tag2': 'Another Value'}" ''' if exists(name, region, key, keyid, profile): conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) ret = _add_tags(conn, name, tags) return ret else: return False def delete_tags(name, tags, region=None, key=None, keyid=None, profile=None): ''' Add the tags on an ELB name name of the ELB tags list of tags to remove CLI Example: .. code-block:: bash salt myminion boto_elb.delete_tags my-elb-name ['TagToRemove1', 'TagToRemove2'] ''' if exists(name, region, key, keyid, profile): conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) ret = _remove_tags(conn, name, tags) return ret else: return False def _build_tag_param_list(params, tags): ''' helper function to build a tag parameter list to send ''' keys = sorted(tags.keys()) i = 1 for key in keys: value = tags[key] params['Tags.member.{0}.Key'.format(i)] = key if value is not None: params['Tags.member.{0}.Value'.format(i)] = value i += 1 def _get_all_tags(conn, load_balancer_names=None): ''' Retrieve all the metadata tags associated with your ELB(s). :type load_balancer_names: list :param load_balancer_names: An optional list of load balancer names. :rtype: list :return: A list of :class:`boto.ec2.elb.tag.Tag` objects ''' params = {} if load_balancer_names: conn.build_list_params(params, load_balancer_names, 'LoadBalancerNames.member.%d') tags = conn.get_object( 'DescribeTags', params, __utils__['boto_elb_tag.get_tag_descriptions'](), verb='POST' ) if tags[load_balancer_names]: return tags[load_balancer_names] else: return None def _add_tags(conn, load_balancer_names, tags): ''' Create new metadata tags for the specified resource ids. :type load_balancer_names: list :param load_balancer_names: A list of load balancer names. :type tags: dict :param tags: A dictionary containing the name/value pairs. If you want to create only a tag name, the value for that tag should be the empty string (e.g. ''). ''' params = {} conn.build_list_params(params, load_balancer_names, 'LoadBalancerNames.member.%d') _build_tag_param_list(params, tags) return conn.get_status('AddTags', params, verb='POST') def _remove_tags(conn, load_balancer_names, tags): ''' Delete metadata tags for the specified resource ids. :type load_balancer_names: list :param load_balancer_names: A list of load balancer names. :type tags: list :param tags: A list containing just tag names for the tags to be deleted. ''' params = {} conn.build_list_params(params, load_balancer_names, 'LoadBalancerNames.member.%d') conn.build_list_params(params, tags, 'Tags.member.%d.Key') return conn.get_status('RemoveTags', params, verb='POST')
saltstack/salt
salt/modules/boto_elb.py
listener_dict_to_tuple
python
def listener_dict_to_tuple(listener): ''' Convert an ELB listener dict into a listener tuple used by certain parts of the AWS ELB API. CLI example: .. code-block:: bash salt myminion boto_elb.listener_dict_to_tuple '{"elb_port":80,"instance_port":80,"elb_protocol":"HTTP"}' ''' # We define all listeners as complex listeners. if 'instance_protocol' not in listener: instance_protocol = listener['elb_protocol'].upper() else: instance_protocol = listener['instance_protocol'].upper() listener_tuple = [listener['elb_port'], listener['instance_port'], listener['elb_protocol'], instance_protocol] if 'certificate' in listener: listener_tuple.append(listener['certificate']) return tuple(listener_tuple)
Convert an ELB listener dict into a listener tuple used by certain parts of the AWS ELB API. CLI example: .. code-block:: bash salt myminion boto_elb.listener_dict_to_tuple '{"elb_port":80,"instance_port":80,"elb_protocol":"HTTP"}'
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_elb.py#L213-L233
null
# -*- coding: utf-8 -*- ''' Connection module for Amazon ELB .. versionadded:: 2014.7.0 :configuration: This module accepts explicit elb credentials but can also utilize IAM roles assigned to the instance through Instance Profiles. Dynamic credentials are then automatically obtained from AWS API and no further configuration is necessary. More Information available at: .. code-block:: text http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/iam-roles-for-amazon-ec2.html If IAM roles are not used you need to specify them either in a pillar or in the minion's config file: .. code-block:: yaml elb.keyid: GKTADJGHEIQSXMKKRBJ08H elb.key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs A region may also be specified in the configuration: .. code-block:: yaml elb.region: us-east-1 If a region is not specified, the default is us-east-1. It's also possible to specify key, keyid and region via a profile, either as a passed in dict, or as a string to pull from pillars or minion config: .. code-block:: yaml myprofile: keyid: GKTADJGHEIQSXMKKRBJ08H key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs region: us-east-1 :depends: boto >= 2.33.0 ''' # keep lint from choking on _get_conn and _cache_id # pylint: disable=E0602 from __future__ import absolute_import, print_function, unicode_literals # Import Python libs import logging import time log = logging.getLogger(__name__) # Import Salt libs import salt.utils.json import salt.utils.odict as odict import salt.utils.versions # Import third party libs from salt.ext import six try: import boto import boto.ec2 # pylint: enable=unused-import from boto.ec2.elb import HealthCheck from boto.ec2.elb.attributes import AccessLogAttribute from boto.ec2.elb.attributes import ConnectionDrainingAttribute from boto.ec2.elb.attributes import ConnectionSettingAttribute from boto.ec2.elb.attributes import CrossZoneLoadBalancingAttribute logging.getLogger('boto').setLevel(logging.CRITICAL) HAS_BOTO = True except ImportError: HAS_BOTO = False def __virtual__(): ''' Only load if boto libraries exist. ''' # connection settings were added in 2.33.0 has_boto_reqs = salt.utils.versions.check_boto_reqs( boto_ver='2.33.0', check_boto3=False ) if has_boto_reqs is True: __utils__['boto.assign_funcs'](__name__, 'elb', module='ec2.elb', pack=__salt__) return has_boto_reqs def exists(name, region=None, key=None, keyid=None, profile=None): ''' Check to see if an ELB exists. CLI example: .. code-block:: bash salt myminion boto_elb.exists myelb region=us-east-1 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: elb = conn.get_all_load_balancers(load_balancer_names=[name]) if elb: return True else: log.debug('The load balancer does not exist in region %s', region) return False except boto.exception.BotoServerError as error: log.warning(error) return False def get_all_elbs(region=None, key=None, keyid=None, profile=None): ''' Return all load balancers associated with an account CLI example: .. code-block:: bash salt myminion boto_elb.get_all_elbs region=us-east-1 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: return [e for e in conn.get_all_load_balancers()] except boto.exception.BotoServerError as error: log.warning(error) return [] def list_elbs(region=None, key=None, keyid=None, profile=None): ''' Return names of all load balancers associated with an account CLI example: .. code-block:: bash salt myminion boto_elb.list_elbs region=us-east-1 ''' return [e.name for e in get_all_elbs(region=region, key=key, keyid=keyid, profile=profile)] def get_elb_config(name, region=None, key=None, keyid=None, profile=None): ''' Get an ELB configuration. CLI example: .. code-block:: bash salt myminion boto_elb.exists myelb region=us-east-1 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) retries = 30 while retries: try: lb = conn.get_all_load_balancers(load_balancer_names=[name]) lb = lb[0] ret = {} ret['availability_zones'] = lb.availability_zones listeners = [] for _listener in lb.listeners: listener_dict = {} listener_dict['elb_port'] = _listener.load_balancer_port listener_dict['elb_protocol'] = _listener.protocol listener_dict['instance_port'] = _listener.instance_port listener_dict['instance_protocol'] = _listener.instance_protocol listener_dict['policies'] = _listener.policy_names if _listener.ssl_certificate_id: listener_dict['certificate'] = _listener.ssl_certificate_id listeners.append(listener_dict) ret['listeners'] = listeners backends = [] for _backend in lb.backends: bs_dict = {} bs_dict['instance_port'] = _backend.instance_port bs_dict['policies'] = [p.policy_name for p in _backend.policies] backends.append(bs_dict) ret['backends'] = backends ret['subnets'] = lb.subnets ret['security_groups'] = lb.security_groups ret['scheme'] = lb.scheme ret['dns_name'] = lb.dns_name ret['tags'] = _get_all_tags(conn, name) lb_policy_lists = [ lb.policies.app_cookie_stickiness_policies, lb.policies.lb_cookie_stickiness_policies, lb.policies.other_policies ] policies = [] for policy_list in lb_policy_lists: policies += [p.policy_name for p in policy_list] ret['policies'] = policies return ret except boto.exception.BotoServerError as error: if error.error_code == 'Throttling': log.debug('Throttled by AWS API, will retry in 5 seconds.') time.sleep(5) retries -= 1 continue log.error('Error fetching config for ELB %s: %s', name, error.message) log.error(error) return {} return {} def create(name, availability_zones, listeners, subnets=None, security_groups=None, scheme='internet-facing', region=None, key=None, keyid=None, profile=None): ''' Create an ELB CLI example to create an ELB: .. code-block:: bash salt myminion boto_elb.create myelb '["us-east-1a", "us-east-1e"]' '{"elb_port": 443, "elb_protocol": "HTTPS", ...}' region=us-east-1 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if exists(name, region, key, keyid, profile): return True if isinstance(availability_zones, six.string_types): availability_zones = salt.utils.json.loads(availability_zones) if isinstance(listeners, six.string_types): listeners = salt.utils.json.loads(listeners) _complex_listeners = [] for listener in listeners: _complex_listeners.append(listener_dict_to_tuple(listener)) try: lb = conn.create_load_balancer(name=name, zones=availability_zones, subnets=subnets, security_groups=security_groups, scheme=scheme, complex_listeners=_complex_listeners) if lb: log.info('Created ELB %s', name) return True else: log.error('Failed to create ELB %s', name) return False except boto.exception.BotoServerError as error: log.error('Failed to create ELB %s: %s: %s', name, error.error_code, error.message, exc_info_on_loglevel=logging.DEBUG) return False def delete(name, region=None, key=None, keyid=None, profile=None): ''' Delete an ELB. CLI example to delete an ELB: .. code-block:: bash salt myminion boto_elb.delete myelb region=us-east-1 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not exists(name, region, key, keyid, profile): return True try: conn.delete_load_balancer(name) log.info('Deleted ELB %s.', name) return True except boto.exception.BotoServerError as error: log.error('Failed to delete ELB %s', name, exc_info_on_loglevel=logging.DEBUG) return False def create_listeners(name, listeners, region=None, key=None, keyid=None, profile=None): ''' Create listeners on an ELB. CLI example: .. code-block:: bash salt myminion boto_elb.create_listeners myelb '[["HTTPS", "HTTP", 443, 80, "arn:aws:iam::11 11111:server-certificate/mycert"]]' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if isinstance(listeners, six.string_types): listeners = salt.utils.json.loads(listeners) _complex_listeners = [] for listener in listeners: _complex_listeners.append(listener_dict_to_tuple(listener)) try: conn.create_load_balancer_listeners(name, [], _complex_listeners) log.info('Created ELB listeners on %s', name) return True except boto.exception.BotoServerError as error: log.error('Failed to create ELB listeners on %s: %s', name, error, exc_info_on_loglevel=logging.DEBUG) return False def delete_listeners(name, ports, region=None, key=None, keyid=None, profile=None): ''' Delete listeners on an ELB. CLI example: .. code-block:: bash salt myminion boto_elb.delete_listeners myelb '[80,443]' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if isinstance(ports, six.string_types): ports = salt.utils.json.loads(ports) try: conn.delete_load_balancer_listeners(name, ports) log.info('Deleted ELB listeners on %s', name) return True except boto.exception.BotoServerError as error: log.error('Failed to delete ELB listeners on %s: %s', name, error, exc_info_on_loglevel=logging.DEBUG) return False def apply_security_groups(name, security_groups, region=None, key=None, keyid=None, profile=None): ''' Apply security groups to ELB. CLI example: .. code-block:: bash salt myminion boto_elb.apply_security_groups myelb '["mysecgroup1"]' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if isinstance(security_groups, six.string_types): security_groups = salt.utils.json.loads(security_groups) try: conn.apply_security_groups_to_lb(name, security_groups) log.info('Applied security_groups on ELB %s', name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to appply security_groups on ELB %s: %s', name, e.message) return False def enable_availability_zones(name, availability_zones, region=None, key=None, keyid=None, profile=None): ''' Enable availability zones for ELB. CLI example: .. code-block:: bash salt myminion boto_elb.enable_availability_zones myelb '["us-east-1a"]' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if isinstance(availability_zones, six.string_types): availability_zones = salt.utils.json.loads(availability_zones) try: conn.enable_availability_zones(name, availability_zones) log.info('Enabled availability_zones on ELB %s', name) return True except boto.exception.BotoServerError as error: log.error('Failed to enable availability_zones on ELB %s: %s', name, error) return False def disable_availability_zones(name, availability_zones, region=None, key=None, keyid=None, profile=None): ''' Disable availability zones for ELB. CLI example: .. code-block:: bash salt myminion boto_elb.disable_availability_zones myelb '["us-east-1a"]' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if isinstance(availability_zones, six.string_types): availability_zones = salt.utils.json.loads(availability_zones) try: conn.disable_availability_zones(name, availability_zones) log.info('Disabled availability_zones on ELB %s', name) return True except boto.exception.BotoServerError as error: log.error('Failed to disable availability_zones on ELB %s: %s', name, error, exc_info_on_loglevel=logging.DEBUG) return False def attach_subnets(name, subnets, region=None, key=None, keyid=None, profile=None): ''' Attach ELB to subnets. CLI example: .. code-block:: bash salt myminion boto_elb.attach_subnets myelb '["mysubnet"]' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if isinstance(subnets, six.string_types): subnets = salt.utils.json.loads(subnets) try: conn.attach_lb_to_subnets(name, subnets) log.info('Attached ELB %s on subnets.', name) return True except boto.exception.BotoServerError as error: log.error('Failed to attach ELB %s on subnets: %s', name, error, exc_info_on_loglevel=logging.DEBUG) return False def detach_subnets(name, subnets, region=None, key=None, keyid=None, profile=None): ''' Detach ELB from subnets. CLI example: .. code-block:: bash salt myminion boto_elb.detach_subnets myelb '["mysubnet"]' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if isinstance(subnets, six.string_types): subnets = salt.utils.json.loads(subnets) try: conn.detach_lb_from_subnets(name, subnets) log.info('Detached ELB %s from subnets.', name) return True except boto.exception.BotoServerError as error: log.error('Failed to detach ELB %s from subnets: %s', name, error, exc_info_on_loglevel=logging.DEBUG) return False def get_attributes(name, region=None, key=None, keyid=None, profile=None): ''' Check to see if attributes are set on an ELB. CLI example: .. code-block:: bash salt myminion boto_elb.get_attributes myelb ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) retries = 30 while retries: try: lbattrs = conn.get_all_lb_attributes(name) ret = odict.OrderedDict() ret['access_log'] = odict.OrderedDict() ret['cross_zone_load_balancing'] = odict.OrderedDict() ret['connection_draining'] = odict.OrderedDict() ret['connecting_settings'] = odict.OrderedDict() al = lbattrs.access_log czlb = lbattrs.cross_zone_load_balancing cd = lbattrs.connection_draining cs = lbattrs.connecting_settings ret['access_log']['enabled'] = al.enabled ret['access_log']['s3_bucket_name'] = al.s3_bucket_name ret['access_log']['s3_bucket_prefix'] = al.s3_bucket_prefix ret['access_log']['emit_interval'] = al.emit_interval ret['cross_zone_load_balancing']['enabled'] = czlb.enabled ret['connection_draining']['enabled'] = cd.enabled ret['connection_draining']['timeout'] = cd.timeout ret['connecting_settings']['idle_timeout'] = cs.idle_timeout return ret except boto.exception.BotoServerError as e: if e.error_code == 'Throttling': log.debug("Throttled by AWS API, will retry in 5 seconds...") time.sleep(5) retries -= 1 continue log.error('ELB %s does not exist: %s', name, e.message) return {} return {} def set_attributes(name, attributes, region=None, key=None, keyid=None, profile=None): ''' Set attributes on an ELB. name (string) Name of the ELB instance to set attributes for attributes A dict of attributes to set. Valid attributes are: access_log (dict) enabled (bool) Enable storage of access logs. s3_bucket_name (string) The name of the S3 bucket to place logs. s3_bucket_prefix (string) Prefix for the log file name. emit_interval (int) Interval for storing logs in S3 in minutes. Valid values are 5 and 60. connection_draining (dict) enabled (bool) Enable connection draining. timeout (int) Maximum allowed time in seconds for sending existing connections to an instance that is deregistering or unhealthy. Default is 300. cross_zone_load_balancing (dict) enabled (bool) Enable cross-zone load balancing. CLI example to set attributes on an ELB: .. code-block:: bash salt myminion boto_elb.set_attributes myelb '{"access_log": {"enabled": "true", "s3_bucket_name": "mybucket", "s3_bucket_prefix": "mylogs/", "emit_interval": "5"}}' region=us-east-1 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) al = attributes.get('access_log', {}) czlb = attributes.get('cross_zone_load_balancing', {}) cd = attributes.get('connection_draining', {}) cs = attributes.get('connecting_settings', {}) if not al and not czlb and not cd and not cs: log.error('No supported attributes for ELB.') return False if al: _al = AccessLogAttribute() _al.enabled = al.get('enabled', False) if not _al.enabled: msg = 'Access log attribute configured, but enabled config missing' log.error(msg) return False _al.s3_bucket_name = al.get('s3_bucket_name', None) _al.s3_bucket_prefix = al.get('s3_bucket_prefix', None) _al.emit_interval = al.get('emit_interval', None) added_attr = conn.modify_lb_attribute(name, 'accessLog', _al) if added_attr: log.info('Added access_log attribute to %s elb.', name) else: log.error('Failed to add access_log attribute to %s elb.', name) return False if czlb: _czlb = CrossZoneLoadBalancingAttribute() _czlb.enabled = czlb['enabled'] added_attr = conn.modify_lb_attribute(name, 'crossZoneLoadBalancing', _czlb.enabled) if added_attr: log.info('Added cross_zone_load_balancing attribute to %s elb.', name) else: log.error('Failed to add cross_zone_load_balancing attribute.') return False if cd: _cd = ConnectionDrainingAttribute() _cd.enabled = cd['enabled'] _cd.timeout = cd.get('timeout', 300) added_attr = conn.modify_lb_attribute(name, 'connectionDraining', _cd) if added_attr: log.info('Added connection_draining attribute to %s elb.', name) else: log.error('Failed to add connection_draining attribute.') return False if cs: _cs = ConnectionSettingAttribute() _cs.idle_timeout = cs.get('idle_timeout', 60) added_attr = conn.modify_lb_attribute(name, 'connectingSettings', _cs) if added_attr: log.info('Added connecting_settings attribute to %s elb.', name) else: log.error('Failed to add connecting_settings attribute.') return False return True def get_health_check(name, region=None, key=None, keyid=None, profile=None): ''' Get the health check configured for this ELB. CLI example: .. code-block:: bash salt myminion boto_elb.get_health_check myelb ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) retries = 30 while True: try: lb = conn.get_all_load_balancers(load_balancer_names=[name]) lb = lb[0] ret = odict.OrderedDict() hc = lb.health_check ret['interval'] = hc.interval ret['target'] = hc.target ret['healthy_threshold'] = hc.healthy_threshold ret['timeout'] = hc.timeout ret['unhealthy_threshold'] = hc.unhealthy_threshold return ret except boto.exception.BotoServerError as e: if retries and e.code == 'Throttling': log.debug('Throttled by AWS API, will retry in 5 seconds.') time.sleep(5) retries -= 1 continue log.error('ELB %s not found.', name, exc_info_on_logleve=logging.DEBUG) return {} def set_health_check(name, health_check, region=None, key=None, keyid=None, profile=None): ''' Set attributes on an ELB. CLI example to set attributes on an ELB: .. code-block:: bash salt myminion boto_elb.set_health_check myelb '{"target": "HTTP:80/"}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) retries = 30 hc = HealthCheck(**health_check) while True: try: conn.configure_health_check(name, hc) log.info('Configured health check on ELB %s', name) return True except boto.exception.BotoServerError as error: if retries and e.code == 'Throttling': log.debug('Throttled by AWS API, will retry in 5 seconds.') time.sleep(5) retries -= 1 continue log.exception('Failed to configure health check on ELB %s', name) return False def register_instances(name, instances, region=None, key=None, keyid=None, profile=None): ''' Register instances with an ELB. Instances is either a string instance id or a list of string instance id's. Returns: - ``True``: instance(s) registered successfully - ``False``: instance(s) failed to be registered CLI example: .. code-block:: bash salt myminion boto_elb.register_instances myelb instance_id salt myminion boto_elb.register_instances myelb "[instance_id,instance_id]" ''' # convert instances to list type, enabling consistent use of instances # variable throughout the register_instances method if isinstance(instances, six.string_types) or isinstance(instances, six.text_type): instances = [instances] conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: registered_instances = conn.register_instances(name, instances) except boto.exception.BotoServerError as error: log.warning(error) return False registered_instance_ids = [instance.id for instance in registered_instances] # register_failues is a set that will contain any instances that were not # able to be registered with the given ELB register_failures = set(instances).difference(set(registered_instance_ids)) if register_failures: log.warning('Instance(s): %s not registered with ELB %s.', list(register_failures), name) register_result = False else: register_result = True return register_result def deregister_instances(name, instances, region=None, key=None, keyid=None, profile=None): ''' Deregister instances with an ELB. Instances is either a string instance id or a list of string instance id's. Returns: - ``True``: instance(s) deregistered successfully - ``False``: instance(s) failed to be deregistered - ``None``: instance(s) not valid or not registered, no action taken CLI example: .. code-block:: bash salt myminion boto_elb.deregister_instances myelb instance_id salt myminion boto_elb.deregister_instances myelb "[instance_id, instance_id]" ''' # convert instances to list type, enabling consistent use of instances # variable throughout the deregister_instances method if isinstance(instances, six.string_types) or isinstance(instances, six.text_type): instances = [instances] conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: registered_instances = conn.deregister_instances(name, instances) except boto.exception.BotoServerError as error: # if the instance(s) given as an argument are not members of the ELB # boto returns error.error_code == 'InvalidInstance' # deregister_instances returns "None" because the instances are # effectively deregistered from ELB if error.error_code == 'InvalidInstance': log.warning( 'One or more of instance(s) %s are not part of ELB %s. ' 'deregister_instances not performed.', instances, name ) return None else: log.warning(error) return False registered_instance_ids = [instance.id for instance in registered_instances] # deregister_failures is a set that will contain any instances that were # unable to be deregistered from the given ELB deregister_failures = set(instances).intersection(set(registered_instance_ids)) if deregister_failures: log.warning( 'Instance(s): %s not deregistered from ELB %s.', list(deregister_failures), name ) deregister_result = False else: deregister_result = True return deregister_result def set_instances(name, instances, test=False, region=None, key=None, keyid=None, profile=None): ''' Set the instances assigned to an ELB to exactly the list given CLI example: .. code-block:: bash salt myminion boto_elb.set_instances myelb region=us-east-1 instances="[instance_id,instance_id]" ''' ret = True current = set([i['instance_id'] for i in get_instance_health(name, region, key, keyid, profile)]) desired = set(instances) add = desired - current remove = current - desired if test: return bool(add or remove) if remove: if deregister_instances(name, list(remove), region, key, keyid, profile) is False: ret = False if add: if register_instances(name, list(add), region, key, keyid, profile) is False: ret = False return ret def get_instance_health(name, region=None, key=None, keyid=None, profile=None, instances=None): ''' Get a list of instances and their health state CLI example: .. code-block:: bash salt myminion boto_elb.get_instance_health myelb salt myminion boto_elb.get_instance_health myelb region=us-east-1 instances="[instance_id,instance_id]" ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: instance_states = conn.describe_instance_health(name, instances) ret = [] for _instance in instance_states: ret.append({'instance_id': _instance.instance_id, 'description': _instance.description, 'state': _instance.state, 'reason_code': _instance.reason_code }) return ret except boto.exception.BotoServerError as error: log.debug(error) return [] def create_policy(name, policy_name, policy_type, policy, region=None, key=None, keyid=None, profile=None): ''' Create an ELB policy. .. versionadded:: 2016.3.0 CLI example: .. code-block:: bash salt myminion boto_elb.create_policy myelb mypolicy LBCookieStickinessPolicyType '{"CookieExpirationPeriod": 3600}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not exists(name, region, key, keyid, profile): return False try: success = conn.create_lb_policy(name, policy_name, policy_type, policy) if success: log.info('Created policy %s on ELB %s', policy_name, name) return True else: log.error('Failed to create policy %s on ELB %s', policy_name, name) return False except boto.exception.BotoServerError as e: log.error('Failed to create policy %s on ELB %s: %s', policy_name, name, e.message, exc_info_on_loglevel=logging.DEBUG) return False def delete_policy(name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Delete an ELB policy. .. versionadded:: 2016.3.0 CLI example: .. code-block:: bash salt myminion boto_elb.delete_policy myelb mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not exists(name, region, key, keyid, profile): return True try: conn.delete_lb_policy(name, policy_name) log.info('Deleted policy %s on ELB %s', policy_name, name) return True except boto.exception.BotoServerError as e: log.error('Failed to delete policy %s on ELB %s: %s', policy_name, name, e.message, exc_info_on_loglevel=logging.DEBUG) return False def set_listener_policy(name, port, policies=None, region=None, key=None, keyid=None, profile=None): ''' Set the policies of an ELB listener. .. versionadded:: 2016.3.0 CLI example: .. code-block:: Bash salt myminion boto_elb.set_listener_policy myelb 443 "[policy1,policy2]" ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not exists(name, region, key, keyid, profile): return True if policies is None: policies = [] try: conn.set_lb_policies_of_listener(name, port, policies) log.info('Set policies %s on ELB %s listener %s', policies, name, port) except boto.exception.BotoServerError as e: log.info('Failed to set policy %s on ELB %s listener %s: %s', policies, name, port, e.message, exc_info_on_loglevel=logging.DEBUG) return False return True def set_backend_policy(name, port, policies=None, region=None, key=None, keyid=None, profile=None): ''' Set the policies of an ELB backend server. CLI example: salt myminion boto_elb.set_backend_policy myelb 443 "[policy1,policy2]" ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not exists(name, region, key, keyid, profile): return True if policies is None: policies = [] try: conn.set_lb_policies_of_backend_server(name, port, policies) log.info('Set policies %s on ELB %s backend server %s', policies, name, port) except boto.exception.BotoServerError as e: log.info('Failed to set policy %s on ELB %s backend server %s: %s', policies, name, port, e.message, exc_info_on_loglevel=logging.DEBUG) return False return True def set_tags(name, tags, region=None, key=None, keyid=None, profile=None): ''' Add the tags on an ELB .. versionadded:: 2016.3.0 name name of the ELB tags dict of name/value pair tags CLI Example: .. code-block:: bash salt myminion boto_elb.set_tags my-elb-name "{'Tag1': 'Value', 'Tag2': 'Another Value'}" ''' if exists(name, region, key, keyid, profile): conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) ret = _add_tags(conn, name, tags) return ret else: return False def delete_tags(name, tags, region=None, key=None, keyid=None, profile=None): ''' Add the tags on an ELB name name of the ELB tags list of tags to remove CLI Example: .. code-block:: bash salt myminion boto_elb.delete_tags my-elb-name ['TagToRemove1', 'TagToRemove2'] ''' if exists(name, region, key, keyid, profile): conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) ret = _remove_tags(conn, name, tags) return ret else: return False def _build_tag_param_list(params, tags): ''' helper function to build a tag parameter list to send ''' keys = sorted(tags.keys()) i = 1 for key in keys: value = tags[key] params['Tags.member.{0}.Key'.format(i)] = key if value is not None: params['Tags.member.{0}.Value'.format(i)] = value i += 1 def _get_all_tags(conn, load_balancer_names=None): ''' Retrieve all the metadata tags associated with your ELB(s). :type load_balancer_names: list :param load_balancer_names: An optional list of load balancer names. :rtype: list :return: A list of :class:`boto.ec2.elb.tag.Tag` objects ''' params = {} if load_balancer_names: conn.build_list_params(params, load_balancer_names, 'LoadBalancerNames.member.%d') tags = conn.get_object( 'DescribeTags', params, __utils__['boto_elb_tag.get_tag_descriptions'](), verb='POST' ) if tags[load_balancer_names]: return tags[load_balancer_names] else: return None def _add_tags(conn, load_balancer_names, tags): ''' Create new metadata tags for the specified resource ids. :type load_balancer_names: list :param load_balancer_names: A list of load balancer names. :type tags: dict :param tags: A dictionary containing the name/value pairs. If you want to create only a tag name, the value for that tag should be the empty string (e.g. ''). ''' params = {} conn.build_list_params(params, load_balancer_names, 'LoadBalancerNames.member.%d') _build_tag_param_list(params, tags) return conn.get_status('AddTags', params, verb='POST') def _remove_tags(conn, load_balancer_names, tags): ''' Delete metadata tags for the specified resource ids. :type load_balancer_names: list :param load_balancer_names: A list of load balancer names. :type tags: list :param tags: A list containing just tag names for the tags to be deleted. ''' params = {} conn.build_list_params(params, load_balancer_names, 'LoadBalancerNames.member.%d') conn.build_list_params(params, tags, 'Tags.member.%d.Key') return conn.get_status('RemoveTags', params, verb='POST')
saltstack/salt
salt/modules/boto_elb.py
create
python
def create(name, availability_zones, listeners, subnets=None, security_groups=None, scheme='internet-facing', region=None, key=None, keyid=None, profile=None): ''' Create an ELB CLI example to create an ELB: .. code-block:: bash salt myminion boto_elb.create myelb '["us-east-1a", "us-east-1e"]' '{"elb_port": 443, "elb_protocol": "HTTPS", ...}' region=us-east-1 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if exists(name, region, key, keyid, profile): return True if isinstance(availability_zones, six.string_types): availability_zones = salt.utils.json.loads(availability_zones) if isinstance(listeners, six.string_types): listeners = salt.utils.json.loads(listeners) _complex_listeners = [] for listener in listeners: _complex_listeners.append(listener_dict_to_tuple(listener)) try: lb = conn.create_load_balancer(name=name, zones=availability_zones, subnets=subnets, security_groups=security_groups, scheme=scheme, complex_listeners=_complex_listeners) if lb: log.info('Created ELB %s', name) return True else: log.error('Failed to create ELB %s', name) return False except boto.exception.BotoServerError as error: log.error('Failed to create ELB %s: %s: %s', name, error.error_code, error.message, exc_info_on_loglevel=logging.DEBUG) return False
Create an ELB CLI example to create an ELB: .. code-block:: bash salt myminion boto_elb.create myelb '["us-east-1a", "us-east-1e"]' '{"elb_port": 443, "elb_protocol": "HTTPS", ...}' region=us-east-1
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_elb.py#L236-L276
[ "def exists(name, region=None, key=None, keyid=None, profile=None):\n '''\n Check to see if an ELB exists.\n\n CLI example:\n\n .. code-block:: bash\n\n salt myminion boto_elb.exists myelb region=us-east-1\n '''\n conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)\n\n try:\n elb = conn.get_all_load_balancers(load_balancer_names=[name])\n if elb:\n return True\n else:\n log.debug('The load balancer does not exist in region %s', region)\n return False\n except boto.exception.BotoServerError as error:\n log.warning(error)\n return False\n", "def loads(s, **kwargs):\n '''\n .. versionadded:: 2018.3.0\n\n Wraps json.loads and prevents a traceback in the event that a bytestring is\n passed to the function. (Python < 3.6 cannot load bytestrings)\n\n You can pass an alternate json module (loaded via import_json() above)\n using the _json_module argument)\n '''\n json_module = kwargs.pop('_json_module', json)\n try:\n return json_module.loads(s, **kwargs)\n except TypeError as exc:\n # json.loads cannot load bytestrings in Python < 3.6\n if six.PY3 and isinstance(s, bytes):\n return json_module.loads(salt.utils.stringutils.to_unicode(s), **kwargs)\n else:\n raise exc\n", "def listener_dict_to_tuple(listener):\n '''\n Convert an ELB listener dict into a listener tuple used by certain parts of\n the AWS ELB API.\n\n CLI example:\n\n .. code-block:: bash\n\n salt myminion boto_elb.listener_dict_to_tuple '{\"elb_port\":80,\"instance_port\":80,\"elb_protocol\":\"HTTP\"}'\n '''\n # We define all listeners as complex listeners.\n if 'instance_protocol' not in listener:\n instance_protocol = listener['elb_protocol'].upper()\n else:\n instance_protocol = listener['instance_protocol'].upper()\n listener_tuple = [listener['elb_port'], listener['instance_port'],\n listener['elb_protocol'], instance_protocol]\n if 'certificate' in listener:\n listener_tuple.append(listener['certificate'])\n return tuple(listener_tuple)\n" ]
# -*- coding: utf-8 -*- ''' Connection module for Amazon ELB .. versionadded:: 2014.7.0 :configuration: This module accepts explicit elb credentials but can also utilize IAM roles assigned to the instance through Instance Profiles. Dynamic credentials are then automatically obtained from AWS API and no further configuration is necessary. More Information available at: .. code-block:: text http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/iam-roles-for-amazon-ec2.html If IAM roles are not used you need to specify them either in a pillar or in the minion's config file: .. code-block:: yaml elb.keyid: GKTADJGHEIQSXMKKRBJ08H elb.key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs A region may also be specified in the configuration: .. code-block:: yaml elb.region: us-east-1 If a region is not specified, the default is us-east-1. It's also possible to specify key, keyid and region via a profile, either as a passed in dict, or as a string to pull from pillars or minion config: .. code-block:: yaml myprofile: keyid: GKTADJGHEIQSXMKKRBJ08H key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs region: us-east-1 :depends: boto >= 2.33.0 ''' # keep lint from choking on _get_conn and _cache_id # pylint: disable=E0602 from __future__ import absolute_import, print_function, unicode_literals # Import Python libs import logging import time log = logging.getLogger(__name__) # Import Salt libs import salt.utils.json import salt.utils.odict as odict import salt.utils.versions # Import third party libs from salt.ext import six try: import boto import boto.ec2 # pylint: enable=unused-import from boto.ec2.elb import HealthCheck from boto.ec2.elb.attributes import AccessLogAttribute from boto.ec2.elb.attributes import ConnectionDrainingAttribute from boto.ec2.elb.attributes import ConnectionSettingAttribute from boto.ec2.elb.attributes import CrossZoneLoadBalancingAttribute logging.getLogger('boto').setLevel(logging.CRITICAL) HAS_BOTO = True except ImportError: HAS_BOTO = False def __virtual__(): ''' Only load if boto libraries exist. ''' # connection settings were added in 2.33.0 has_boto_reqs = salt.utils.versions.check_boto_reqs( boto_ver='2.33.0', check_boto3=False ) if has_boto_reqs is True: __utils__['boto.assign_funcs'](__name__, 'elb', module='ec2.elb', pack=__salt__) return has_boto_reqs def exists(name, region=None, key=None, keyid=None, profile=None): ''' Check to see if an ELB exists. CLI example: .. code-block:: bash salt myminion boto_elb.exists myelb region=us-east-1 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: elb = conn.get_all_load_balancers(load_balancer_names=[name]) if elb: return True else: log.debug('The load balancer does not exist in region %s', region) return False except boto.exception.BotoServerError as error: log.warning(error) return False def get_all_elbs(region=None, key=None, keyid=None, profile=None): ''' Return all load balancers associated with an account CLI example: .. code-block:: bash salt myminion boto_elb.get_all_elbs region=us-east-1 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: return [e for e in conn.get_all_load_balancers()] except boto.exception.BotoServerError as error: log.warning(error) return [] def list_elbs(region=None, key=None, keyid=None, profile=None): ''' Return names of all load balancers associated with an account CLI example: .. code-block:: bash salt myminion boto_elb.list_elbs region=us-east-1 ''' return [e.name for e in get_all_elbs(region=region, key=key, keyid=keyid, profile=profile)] def get_elb_config(name, region=None, key=None, keyid=None, profile=None): ''' Get an ELB configuration. CLI example: .. code-block:: bash salt myminion boto_elb.exists myelb region=us-east-1 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) retries = 30 while retries: try: lb = conn.get_all_load_balancers(load_balancer_names=[name]) lb = lb[0] ret = {} ret['availability_zones'] = lb.availability_zones listeners = [] for _listener in lb.listeners: listener_dict = {} listener_dict['elb_port'] = _listener.load_balancer_port listener_dict['elb_protocol'] = _listener.protocol listener_dict['instance_port'] = _listener.instance_port listener_dict['instance_protocol'] = _listener.instance_protocol listener_dict['policies'] = _listener.policy_names if _listener.ssl_certificate_id: listener_dict['certificate'] = _listener.ssl_certificate_id listeners.append(listener_dict) ret['listeners'] = listeners backends = [] for _backend in lb.backends: bs_dict = {} bs_dict['instance_port'] = _backend.instance_port bs_dict['policies'] = [p.policy_name for p in _backend.policies] backends.append(bs_dict) ret['backends'] = backends ret['subnets'] = lb.subnets ret['security_groups'] = lb.security_groups ret['scheme'] = lb.scheme ret['dns_name'] = lb.dns_name ret['tags'] = _get_all_tags(conn, name) lb_policy_lists = [ lb.policies.app_cookie_stickiness_policies, lb.policies.lb_cookie_stickiness_policies, lb.policies.other_policies ] policies = [] for policy_list in lb_policy_lists: policies += [p.policy_name for p in policy_list] ret['policies'] = policies return ret except boto.exception.BotoServerError as error: if error.error_code == 'Throttling': log.debug('Throttled by AWS API, will retry in 5 seconds.') time.sleep(5) retries -= 1 continue log.error('Error fetching config for ELB %s: %s', name, error.message) log.error(error) return {} return {} def listener_dict_to_tuple(listener): ''' Convert an ELB listener dict into a listener tuple used by certain parts of the AWS ELB API. CLI example: .. code-block:: bash salt myminion boto_elb.listener_dict_to_tuple '{"elb_port":80,"instance_port":80,"elb_protocol":"HTTP"}' ''' # We define all listeners as complex listeners. if 'instance_protocol' not in listener: instance_protocol = listener['elb_protocol'].upper() else: instance_protocol = listener['instance_protocol'].upper() listener_tuple = [listener['elb_port'], listener['instance_port'], listener['elb_protocol'], instance_protocol] if 'certificate' in listener: listener_tuple.append(listener['certificate']) return tuple(listener_tuple) def delete(name, region=None, key=None, keyid=None, profile=None): ''' Delete an ELB. CLI example to delete an ELB: .. code-block:: bash salt myminion boto_elb.delete myelb region=us-east-1 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not exists(name, region, key, keyid, profile): return True try: conn.delete_load_balancer(name) log.info('Deleted ELB %s.', name) return True except boto.exception.BotoServerError as error: log.error('Failed to delete ELB %s', name, exc_info_on_loglevel=logging.DEBUG) return False def create_listeners(name, listeners, region=None, key=None, keyid=None, profile=None): ''' Create listeners on an ELB. CLI example: .. code-block:: bash salt myminion boto_elb.create_listeners myelb '[["HTTPS", "HTTP", 443, 80, "arn:aws:iam::11 11111:server-certificate/mycert"]]' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if isinstance(listeners, six.string_types): listeners = salt.utils.json.loads(listeners) _complex_listeners = [] for listener in listeners: _complex_listeners.append(listener_dict_to_tuple(listener)) try: conn.create_load_balancer_listeners(name, [], _complex_listeners) log.info('Created ELB listeners on %s', name) return True except boto.exception.BotoServerError as error: log.error('Failed to create ELB listeners on %s: %s', name, error, exc_info_on_loglevel=logging.DEBUG) return False def delete_listeners(name, ports, region=None, key=None, keyid=None, profile=None): ''' Delete listeners on an ELB. CLI example: .. code-block:: bash salt myminion boto_elb.delete_listeners myelb '[80,443]' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if isinstance(ports, six.string_types): ports = salt.utils.json.loads(ports) try: conn.delete_load_balancer_listeners(name, ports) log.info('Deleted ELB listeners on %s', name) return True except boto.exception.BotoServerError as error: log.error('Failed to delete ELB listeners on %s: %s', name, error, exc_info_on_loglevel=logging.DEBUG) return False def apply_security_groups(name, security_groups, region=None, key=None, keyid=None, profile=None): ''' Apply security groups to ELB. CLI example: .. code-block:: bash salt myminion boto_elb.apply_security_groups myelb '["mysecgroup1"]' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if isinstance(security_groups, six.string_types): security_groups = salt.utils.json.loads(security_groups) try: conn.apply_security_groups_to_lb(name, security_groups) log.info('Applied security_groups on ELB %s', name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to appply security_groups on ELB %s: %s', name, e.message) return False def enable_availability_zones(name, availability_zones, region=None, key=None, keyid=None, profile=None): ''' Enable availability zones for ELB. CLI example: .. code-block:: bash salt myminion boto_elb.enable_availability_zones myelb '["us-east-1a"]' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if isinstance(availability_zones, six.string_types): availability_zones = salt.utils.json.loads(availability_zones) try: conn.enable_availability_zones(name, availability_zones) log.info('Enabled availability_zones on ELB %s', name) return True except boto.exception.BotoServerError as error: log.error('Failed to enable availability_zones on ELB %s: %s', name, error) return False def disable_availability_zones(name, availability_zones, region=None, key=None, keyid=None, profile=None): ''' Disable availability zones for ELB. CLI example: .. code-block:: bash salt myminion boto_elb.disable_availability_zones myelb '["us-east-1a"]' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if isinstance(availability_zones, six.string_types): availability_zones = salt.utils.json.loads(availability_zones) try: conn.disable_availability_zones(name, availability_zones) log.info('Disabled availability_zones on ELB %s', name) return True except boto.exception.BotoServerError as error: log.error('Failed to disable availability_zones on ELB %s: %s', name, error, exc_info_on_loglevel=logging.DEBUG) return False def attach_subnets(name, subnets, region=None, key=None, keyid=None, profile=None): ''' Attach ELB to subnets. CLI example: .. code-block:: bash salt myminion boto_elb.attach_subnets myelb '["mysubnet"]' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if isinstance(subnets, six.string_types): subnets = salt.utils.json.loads(subnets) try: conn.attach_lb_to_subnets(name, subnets) log.info('Attached ELB %s on subnets.', name) return True except boto.exception.BotoServerError as error: log.error('Failed to attach ELB %s on subnets: %s', name, error, exc_info_on_loglevel=logging.DEBUG) return False def detach_subnets(name, subnets, region=None, key=None, keyid=None, profile=None): ''' Detach ELB from subnets. CLI example: .. code-block:: bash salt myminion boto_elb.detach_subnets myelb '["mysubnet"]' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if isinstance(subnets, six.string_types): subnets = salt.utils.json.loads(subnets) try: conn.detach_lb_from_subnets(name, subnets) log.info('Detached ELB %s from subnets.', name) return True except boto.exception.BotoServerError as error: log.error('Failed to detach ELB %s from subnets: %s', name, error, exc_info_on_loglevel=logging.DEBUG) return False def get_attributes(name, region=None, key=None, keyid=None, profile=None): ''' Check to see if attributes are set on an ELB. CLI example: .. code-block:: bash salt myminion boto_elb.get_attributes myelb ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) retries = 30 while retries: try: lbattrs = conn.get_all_lb_attributes(name) ret = odict.OrderedDict() ret['access_log'] = odict.OrderedDict() ret['cross_zone_load_balancing'] = odict.OrderedDict() ret['connection_draining'] = odict.OrderedDict() ret['connecting_settings'] = odict.OrderedDict() al = lbattrs.access_log czlb = lbattrs.cross_zone_load_balancing cd = lbattrs.connection_draining cs = lbattrs.connecting_settings ret['access_log']['enabled'] = al.enabled ret['access_log']['s3_bucket_name'] = al.s3_bucket_name ret['access_log']['s3_bucket_prefix'] = al.s3_bucket_prefix ret['access_log']['emit_interval'] = al.emit_interval ret['cross_zone_load_balancing']['enabled'] = czlb.enabled ret['connection_draining']['enabled'] = cd.enabled ret['connection_draining']['timeout'] = cd.timeout ret['connecting_settings']['idle_timeout'] = cs.idle_timeout return ret except boto.exception.BotoServerError as e: if e.error_code == 'Throttling': log.debug("Throttled by AWS API, will retry in 5 seconds...") time.sleep(5) retries -= 1 continue log.error('ELB %s does not exist: %s', name, e.message) return {} return {} def set_attributes(name, attributes, region=None, key=None, keyid=None, profile=None): ''' Set attributes on an ELB. name (string) Name of the ELB instance to set attributes for attributes A dict of attributes to set. Valid attributes are: access_log (dict) enabled (bool) Enable storage of access logs. s3_bucket_name (string) The name of the S3 bucket to place logs. s3_bucket_prefix (string) Prefix for the log file name. emit_interval (int) Interval for storing logs in S3 in minutes. Valid values are 5 and 60. connection_draining (dict) enabled (bool) Enable connection draining. timeout (int) Maximum allowed time in seconds for sending existing connections to an instance that is deregistering or unhealthy. Default is 300. cross_zone_load_balancing (dict) enabled (bool) Enable cross-zone load balancing. CLI example to set attributes on an ELB: .. code-block:: bash salt myminion boto_elb.set_attributes myelb '{"access_log": {"enabled": "true", "s3_bucket_name": "mybucket", "s3_bucket_prefix": "mylogs/", "emit_interval": "5"}}' region=us-east-1 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) al = attributes.get('access_log', {}) czlb = attributes.get('cross_zone_load_balancing', {}) cd = attributes.get('connection_draining', {}) cs = attributes.get('connecting_settings', {}) if not al and not czlb and not cd and not cs: log.error('No supported attributes for ELB.') return False if al: _al = AccessLogAttribute() _al.enabled = al.get('enabled', False) if not _al.enabled: msg = 'Access log attribute configured, but enabled config missing' log.error(msg) return False _al.s3_bucket_name = al.get('s3_bucket_name', None) _al.s3_bucket_prefix = al.get('s3_bucket_prefix', None) _al.emit_interval = al.get('emit_interval', None) added_attr = conn.modify_lb_attribute(name, 'accessLog', _al) if added_attr: log.info('Added access_log attribute to %s elb.', name) else: log.error('Failed to add access_log attribute to %s elb.', name) return False if czlb: _czlb = CrossZoneLoadBalancingAttribute() _czlb.enabled = czlb['enabled'] added_attr = conn.modify_lb_attribute(name, 'crossZoneLoadBalancing', _czlb.enabled) if added_attr: log.info('Added cross_zone_load_balancing attribute to %s elb.', name) else: log.error('Failed to add cross_zone_load_balancing attribute.') return False if cd: _cd = ConnectionDrainingAttribute() _cd.enabled = cd['enabled'] _cd.timeout = cd.get('timeout', 300) added_attr = conn.modify_lb_attribute(name, 'connectionDraining', _cd) if added_attr: log.info('Added connection_draining attribute to %s elb.', name) else: log.error('Failed to add connection_draining attribute.') return False if cs: _cs = ConnectionSettingAttribute() _cs.idle_timeout = cs.get('idle_timeout', 60) added_attr = conn.modify_lb_attribute(name, 'connectingSettings', _cs) if added_attr: log.info('Added connecting_settings attribute to %s elb.', name) else: log.error('Failed to add connecting_settings attribute.') return False return True def get_health_check(name, region=None, key=None, keyid=None, profile=None): ''' Get the health check configured for this ELB. CLI example: .. code-block:: bash salt myminion boto_elb.get_health_check myelb ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) retries = 30 while True: try: lb = conn.get_all_load_balancers(load_balancer_names=[name]) lb = lb[0] ret = odict.OrderedDict() hc = lb.health_check ret['interval'] = hc.interval ret['target'] = hc.target ret['healthy_threshold'] = hc.healthy_threshold ret['timeout'] = hc.timeout ret['unhealthy_threshold'] = hc.unhealthy_threshold return ret except boto.exception.BotoServerError as e: if retries and e.code == 'Throttling': log.debug('Throttled by AWS API, will retry in 5 seconds.') time.sleep(5) retries -= 1 continue log.error('ELB %s not found.', name, exc_info_on_logleve=logging.DEBUG) return {} def set_health_check(name, health_check, region=None, key=None, keyid=None, profile=None): ''' Set attributes on an ELB. CLI example to set attributes on an ELB: .. code-block:: bash salt myminion boto_elb.set_health_check myelb '{"target": "HTTP:80/"}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) retries = 30 hc = HealthCheck(**health_check) while True: try: conn.configure_health_check(name, hc) log.info('Configured health check on ELB %s', name) return True except boto.exception.BotoServerError as error: if retries and e.code == 'Throttling': log.debug('Throttled by AWS API, will retry in 5 seconds.') time.sleep(5) retries -= 1 continue log.exception('Failed to configure health check on ELB %s', name) return False def register_instances(name, instances, region=None, key=None, keyid=None, profile=None): ''' Register instances with an ELB. Instances is either a string instance id or a list of string instance id's. Returns: - ``True``: instance(s) registered successfully - ``False``: instance(s) failed to be registered CLI example: .. code-block:: bash salt myminion boto_elb.register_instances myelb instance_id salt myminion boto_elb.register_instances myelb "[instance_id,instance_id]" ''' # convert instances to list type, enabling consistent use of instances # variable throughout the register_instances method if isinstance(instances, six.string_types) or isinstance(instances, six.text_type): instances = [instances] conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: registered_instances = conn.register_instances(name, instances) except boto.exception.BotoServerError as error: log.warning(error) return False registered_instance_ids = [instance.id for instance in registered_instances] # register_failues is a set that will contain any instances that were not # able to be registered with the given ELB register_failures = set(instances).difference(set(registered_instance_ids)) if register_failures: log.warning('Instance(s): %s not registered with ELB %s.', list(register_failures), name) register_result = False else: register_result = True return register_result def deregister_instances(name, instances, region=None, key=None, keyid=None, profile=None): ''' Deregister instances with an ELB. Instances is either a string instance id or a list of string instance id's. Returns: - ``True``: instance(s) deregistered successfully - ``False``: instance(s) failed to be deregistered - ``None``: instance(s) not valid or not registered, no action taken CLI example: .. code-block:: bash salt myminion boto_elb.deregister_instances myelb instance_id salt myminion boto_elb.deregister_instances myelb "[instance_id, instance_id]" ''' # convert instances to list type, enabling consistent use of instances # variable throughout the deregister_instances method if isinstance(instances, six.string_types) or isinstance(instances, six.text_type): instances = [instances] conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: registered_instances = conn.deregister_instances(name, instances) except boto.exception.BotoServerError as error: # if the instance(s) given as an argument are not members of the ELB # boto returns error.error_code == 'InvalidInstance' # deregister_instances returns "None" because the instances are # effectively deregistered from ELB if error.error_code == 'InvalidInstance': log.warning( 'One or more of instance(s) %s are not part of ELB %s. ' 'deregister_instances not performed.', instances, name ) return None else: log.warning(error) return False registered_instance_ids = [instance.id for instance in registered_instances] # deregister_failures is a set that will contain any instances that were # unable to be deregistered from the given ELB deregister_failures = set(instances).intersection(set(registered_instance_ids)) if deregister_failures: log.warning( 'Instance(s): %s not deregistered from ELB %s.', list(deregister_failures), name ) deregister_result = False else: deregister_result = True return deregister_result def set_instances(name, instances, test=False, region=None, key=None, keyid=None, profile=None): ''' Set the instances assigned to an ELB to exactly the list given CLI example: .. code-block:: bash salt myminion boto_elb.set_instances myelb region=us-east-1 instances="[instance_id,instance_id]" ''' ret = True current = set([i['instance_id'] for i in get_instance_health(name, region, key, keyid, profile)]) desired = set(instances) add = desired - current remove = current - desired if test: return bool(add or remove) if remove: if deregister_instances(name, list(remove), region, key, keyid, profile) is False: ret = False if add: if register_instances(name, list(add), region, key, keyid, profile) is False: ret = False return ret def get_instance_health(name, region=None, key=None, keyid=None, profile=None, instances=None): ''' Get a list of instances and their health state CLI example: .. code-block:: bash salt myminion boto_elb.get_instance_health myelb salt myminion boto_elb.get_instance_health myelb region=us-east-1 instances="[instance_id,instance_id]" ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: instance_states = conn.describe_instance_health(name, instances) ret = [] for _instance in instance_states: ret.append({'instance_id': _instance.instance_id, 'description': _instance.description, 'state': _instance.state, 'reason_code': _instance.reason_code }) return ret except boto.exception.BotoServerError as error: log.debug(error) return [] def create_policy(name, policy_name, policy_type, policy, region=None, key=None, keyid=None, profile=None): ''' Create an ELB policy. .. versionadded:: 2016.3.0 CLI example: .. code-block:: bash salt myminion boto_elb.create_policy myelb mypolicy LBCookieStickinessPolicyType '{"CookieExpirationPeriod": 3600}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not exists(name, region, key, keyid, profile): return False try: success = conn.create_lb_policy(name, policy_name, policy_type, policy) if success: log.info('Created policy %s on ELB %s', policy_name, name) return True else: log.error('Failed to create policy %s on ELB %s', policy_name, name) return False except boto.exception.BotoServerError as e: log.error('Failed to create policy %s on ELB %s: %s', policy_name, name, e.message, exc_info_on_loglevel=logging.DEBUG) return False def delete_policy(name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Delete an ELB policy. .. versionadded:: 2016.3.0 CLI example: .. code-block:: bash salt myminion boto_elb.delete_policy myelb mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not exists(name, region, key, keyid, profile): return True try: conn.delete_lb_policy(name, policy_name) log.info('Deleted policy %s on ELB %s', policy_name, name) return True except boto.exception.BotoServerError as e: log.error('Failed to delete policy %s on ELB %s: %s', policy_name, name, e.message, exc_info_on_loglevel=logging.DEBUG) return False def set_listener_policy(name, port, policies=None, region=None, key=None, keyid=None, profile=None): ''' Set the policies of an ELB listener. .. versionadded:: 2016.3.0 CLI example: .. code-block:: Bash salt myminion boto_elb.set_listener_policy myelb 443 "[policy1,policy2]" ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not exists(name, region, key, keyid, profile): return True if policies is None: policies = [] try: conn.set_lb_policies_of_listener(name, port, policies) log.info('Set policies %s on ELB %s listener %s', policies, name, port) except boto.exception.BotoServerError as e: log.info('Failed to set policy %s on ELB %s listener %s: %s', policies, name, port, e.message, exc_info_on_loglevel=logging.DEBUG) return False return True def set_backend_policy(name, port, policies=None, region=None, key=None, keyid=None, profile=None): ''' Set the policies of an ELB backend server. CLI example: salt myminion boto_elb.set_backend_policy myelb 443 "[policy1,policy2]" ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not exists(name, region, key, keyid, profile): return True if policies is None: policies = [] try: conn.set_lb_policies_of_backend_server(name, port, policies) log.info('Set policies %s on ELB %s backend server %s', policies, name, port) except boto.exception.BotoServerError as e: log.info('Failed to set policy %s on ELB %s backend server %s: %s', policies, name, port, e.message, exc_info_on_loglevel=logging.DEBUG) return False return True def set_tags(name, tags, region=None, key=None, keyid=None, profile=None): ''' Add the tags on an ELB .. versionadded:: 2016.3.0 name name of the ELB tags dict of name/value pair tags CLI Example: .. code-block:: bash salt myminion boto_elb.set_tags my-elb-name "{'Tag1': 'Value', 'Tag2': 'Another Value'}" ''' if exists(name, region, key, keyid, profile): conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) ret = _add_tags(conn, name, tags) return ret else: return False def delete_tags(name, tags, region=None, key=None, keyid=None, profile=None): ''' Add the tags on an ELB name name of the ELB tags list of tags to remove CLI Example: .. code-block:: bash salt myminion boto_elb.delete_tags my-elb-name ['TagToRemove1', 'TagToRemove2'] ''' if exists(name, region, key, keyid, profile): conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) ret = _remove_tags(conn, name, tags) return ret else: return False def _build_tag_param_list(params, tags): ''' helper function to build a tag parameter list to send ''' keys = sorted(tags.keys()) i = 1 for key in keys: value = tags[key] params['Tags.member.{0}.Key'.format(i)] = key if value is not None: params['Tags.member.{0}.Value'.format(i)] = value i += 1 def _get_all_tags(conn, load_balancer_names=None): ''' Retrieve all the metadata tags associated with your ELB(s). :type load_balancer_names: list :param load_balancer_names: An optional list of load balancer names. :rtype: list :return: A list of :class:`boto.ec2.elb.tag.Tag` objects ''' params = {} if load_balancer_names: conn.build_list_params(params, load_balancer_names, 'LoadBalancerNames.member.%d') tags = conn.get_object( 'DescribeTags', params, __utils__['boto_elb_tag.get_tag_descriptions'](), verb='POST' ) if tags[load_balancer_names]: return tags[load_balancer_names] else: return None def _add_tags(conn, load_balancer_names, tags): ''' Create new metadata tags for the specified resource ids. :type load_balancer_names: list :param load_balancer_names: A list of load balancer names. :type tags: dict :param tags: A dictionary containing the name/value pairs. If you want to create only a tag name, the value for that tag should be the empty string (e.g. ''). ''' params = {} conn.build_list_params(params, load_balancer_names, 'LoadBalancerNames.member.%d') _build_tag_param_list(params, tags) return conn.get_status('AddTags', params, verb='POST') def _remove_tags(conn, load_balancer_names, tags): ''' Delete metadata tags for the specified resource ids. :type load_balancer_names: list :param load_balancer_names: A list of load balancer names. :type tags: list :param tags: A list containing just tag names for the tags to be deleted. ''' params = {} conn.build_list_params(params, load_balancer_names, 'LoadBalancerNames.member.%d') conn.build_list_params(params, tags, 'Tags.member.%d.Key') return conn.get_status('RemoveTags', params, verb='POST')
saltstack/salt
salt/modules/boto_elb.py
delete
python
def delete(name, region=None, key=None, keyid=None, profile=None): ''' Delete an ELB. CLI example to delete an ELB: .. code-block:: bash salt myminion boto_elb.delete myelb region=us-east-1 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not exists(name, region, key, keyid, profile): return True try: conn.delete_load_balancer(name) log.info('Deleted ELB %s.', name) return True except boto.exception.BotoServerError as error: log.error('Failed to delete ELB %s', name, exc_info_on_loglevel=logging.DEBUG) return False
Delete an ELB. CLI example to delete an ELB: .. code-block:: bash salt myminion boto_elb.delete myelb region=us-east-1
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_elb.py#L279-L300
[ "def exists(name, region=None, key=None, keyid=None, profile=None):\n '''\n Check to see if an ELB exists.\n\n CLI example:\n\n .. code-block:: bash\n\n salt myminion boto_elb.exists myelb region=us-east-1\n '''\n conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)\n\n try:\n elb = conn.get_all_load_balancers(load_balancer_names=[name])\n if elb:\n return True\n else:\n log.debug('The load balancer does not exist in region %s', region)\n return False\n except boto.exception.BotoServerError as error:\n log.warning(error)\n return False\n" ]
# -*- coding: utf-8 -*- ''' Connection module for Amazon ELB .. versionadded:: 2014.7.0 :configuration: This module accepts explicit elb credentials but can also utilize IAM roles assigned to the instance through Instance Profiles. Dynamic credentials are then automatically obtained from AWS API and no further configuration is necessary. More Information available at: .. code-block:: text http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/iam-roles-for-amazon-ec2.html If IAM roles are not used you need to specify them either in a pillar or in the minion's config file: .. code-block:: yaml elb.keyid: GKTADJGHEIQSXMKKRBJ08H elb.key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs A region may also be specified in the configuration: .. code-block:: yaml elb.region: us-east-1 If a region is not specified, the default is us-east-1. It's also possible to specify key, keyid and region via a profile, either as a passed in dict, or as a string to pull from pillars or minion config: .. code-block:: yaml myprofile: keyid: GKTADJGHEIQSXMKKRBJ08H key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs region: us-east-1 :depends: boto >= 2.33.0 ''' # keep lint from choking on _get_conn and _cache_id # pylint: disable=E0602 from __future__ import absolute_import, print_function, unicode_literals # Import Python libs import logging import time log = logging.getLogger(__name__) # Import Salt libs import salt.utils.json import salt.utils.odict as odict import salt.utils.versions # Import third party libs from salt.ext import six try: import boto import boto.ec2 # pylint: enable=unused-import from boto.ec2.elb import HealthCheck from boto.ec2.elb.attributes import AccessLogAttribute from boto.ec2.elb.attributes import ConnectionDrainingAttribute from boto.ec2.elb.attributes import ConnectionSettingAttribute from boto.ec2.elb.attributes import CrossZoneLoadBalancingAttribute logging.getLogger('boto').setLevel(logging.CRITICAL) HAS_BOTO = True except ImportError: HAS_BOTO = False def __virtual__(): ''' Only load if boto libraries exist. ''' # connection settings were added in 2.33.0 has_boto_reqs = salt.utils.versions.check_boto_reqs( boto_ver='2.33.0', check_boto3=False ) if has_boto_reqs is True: __utils__['boto.assign_funcs'](__name__, 'elb', module='ec2.elb', pack=__salt__) return has_boto_reqs def exists(name, region=None, key=None, keyid=None, profile=None): ''' Check to see if an ELB exists. CLI example: .. code-block:: bash salt myminion boto_elb.exists myelb region=us-east-1 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: elb = conn.get_all_load_balancers(load_balancer_names=[name]) if elb: return True else: log.debug('The load balancer does not exist in region %s', region) return False except boto.exception.BotoServerError as error: log.warning(error) return False def get_all_elbs(region=None, key=None, keyid=None, profile=None): ''' Return all load balancers associated with an account CLI example: .. code-block:: bash salt myminion boto_elb.get_all_elbs region=us-east-1 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: return [e for e in conn.get_all_load_balancers()] except boto.exception.BotoServerError as error: log.warning(error) return [] def list_elbs(region=None, key=None, keyid=None, profile=None): ''' Return names of all load balancers associated with an account CLI example: .. code-block:: bash salt myminion boto_elb.list_elbs region=us-east-1 ''' return [e.name for e in get_all_elbs(region=region, key=key, keyid=keyid, profile=profile)] def get_elb_config(name, region=None, key=None, keyid=None, profile=None): ''' Get an ELB configuration. CLI example: .. code-block:: bash salt myminion boto_elb.exists myelb region=us-east-1 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) retries = 30 while retries: try: lb = conn.get_all_load_balancers(load_balancer_names=[name]) lb = lb[0] ret = {} ret['availability_zones'] = lb.availability_zones listeners = [] for _listener in lb.listeners: listener_dict = {} listener_dict['elb_port'] = _listener.load_balancer_port listener_dict['elb_protocol'] = _listener.protocol listener_dict['instance_port'] = _listener.instance_port listener_dict['instance_protocol'] = _listener.instance_protocol listener_dict['policies'] = _listener.policy_names if _listener.ssl_certificate_id: listener_dict['certificate'] = _listener.ssl_certificate_id listeners.append(listener_dict) ret['listeners'] = listeners backends = [] for _backend in lb.backends: bs_dict = {} bs_dict['instance_port'] = _backend.instance_port bs_dict['policies'] = [p.policy_name for p in _backend.policies] backends.append(bs_dict) ret['backends'] = backends ret['subnets'] = lb.subnets ret['security_groups'] = lb.security_groups ret['scheme'] = lb.scheme ret['dns_name'] = lb.dns_name ret['tags'] = _get_all_tags(conn, name) lb_policy_lists = [ lb.policies.app_cookie_stickiness_policies, lb.policies.lb_cookie_stickiness_policies, lb.policies.other_policies ] policies = [] for policy_list in lb_policy_lists: policies += [p.policy_name for p in policy_list] ret['policies'] = policies return ret except boto.exception.BotoServerError as error: if error.error_code == 'Throttling': log.debug('Throttled by AWS API, will retry in 5 seconds.') time.sleep(5) retries -= 1 continue log.error('Error fetching config for ELB %s: %s', name, error.message) log.error(error) return {} return {} def listener_dict_to_tuple(listener): ''' Convert an ELB listener dict into a listener tuple used by certain parts of the AWS ELB API. CLI example: .. code-block:: bash salt myminion boto_elb.listener_dict_to_tuple '{"elb_port":80,"instance_port":80,"elb_protocol":"HTTP"}' ''' # We define all listeners as complex listeners. if 'instance_protocol' not in listener: instance_protocol = listener['elb_protocol'].upper() else: instance_protocol = listener['instance_protocol'].upper() listener_tuple = [listener['elb_port'], listener['instance_port'], listener['elb_protocol'], instance_protocol] if 'certificate' in listener: listener_tuple.append(listener['certificate']) return tuple(listener_tuple) def create(name, availability_zones, listeners, subnets=None, security_groups=None, scheme='internet-facing', region=None, key=None, keyid=None, profile=None): ''' Create an ELB CLI example to create an ELB: .. code-block:: bash salt myminion boto_elb.create myelb '["us-east-1a", "us-east-1e"]' '{"elb_port": 443, "elb_protocol": "HTTPS", ...}' region=us-east-1 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if exists(name, region, key, keyid, profile): return True if isinstance(availability_zones, six.string_types): availability_zones = salt.utils.json.loads(availability_zones) if isinstance(listeners, six.string_types): listeners = salt.utils.json.loads(listeners) _complex_listeners = [] for listener in listeners: _complex_listeners.append(listener_dict_to_tuple(listener)) try: lb = conn.create_load_balancer(name=name, zones=availability_zones, subnets=subnets, security_groups=security_groups, scheme=scheme, complex_listeners=_complex_listeners) if lb: log.info('Created ELB %s', name) return True else: log.error('Failed to create ELB %s', name) return False except boto.exception.BotoServerError as error: log.error('Failed to create ELB %s: %s: %s', name, error.error_code, error.message, exc_info_on_loglevel=logging.DEBUG) return False def create_listeners(name, listeners, region=None, key=None, keyid=None, profile=None): ''' Create listeners on an ELB. CLI example: .. code-block:: bash salt myminion boto_elb.create_listeners myelb '[["HTTPS", "HTTP", 443, 80, "arn:aws:iam::11 11111:server-certificate/mycert"]]' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if isinstance(listeners, six.string_types): listeners = salt.utils.json.loads(listeners) _complex_listeners = [] for listener in listeners: _complex_listeners.append(listener_dict_to_tuple(listener)) try: conn.create_load_balancer_listeners(name, [], _complex_listeners) log.info('Created ELB listeners on %s', name) return True except boto.exception.BotoServerError as error: log.error('Failed to create ELB listeners on %s: %s', name, error, exc_info_on_loglevel=logging.DEBUG) return False def delete_listeners(name, ports, region=None, key=None, keyid=None, profile=None): ''' Delete listeners on an ELB. CLI example: .. code-block:: bash salt myminion boto_elb.delete_listeners myelb '[80,443]' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if isinstance(ports, six.string_types): ports = salt.utils.json.loads(ports) try: conn.delete_load_balancer_listeners(name, ports) log.info('Deleted ELB listeners on %s', name) return True except boto.exception.BotoServerError as error: log.error('Failed to delete ELB listeners on %s: %s', name, error, exc_info_on_loglevel=logging.DEBUG) return False def apply_security_groups(name, security_groups, region=None, key=None, keyid=None, profile=None): ''' Apply security groups to ELB. CLI example: .. code-block:: bash salt myminion boto_elb.apply_security_groups myelb '["mysecgroup1"]' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if isinstance(security_groups, six.string_types): security_groups = salt.utils.json.loads(security_groups) try: conn.apply_security_groups_to_lb(name, security_groups) log.info('Applied security_groups on ELB %s', name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to appply security_groups on ELB %s: %s', name, e.message) return False def enable_availability_zones(name, availability_zones, region=None, key=None, keyid=None, profile=None): ''' Enable availability zones for ELB. CLI example: .. code-block:: bash salt myminion boto_elb.enable_availability_zones myelb '["us-east-1a"]' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if isinstance(availability_zones, six.string_types): availability_zones = salt.utils.json.loads(availability_zones) try: conn.enable_availability_zones(name, availability_zones) log.info('Enabled availability_zones on ELB %s', name) return True except boto.exception.BotoServerError as error: log.error('Failed to enable availability_zones on ELB %s: %s', name, error) return False def disable_availability_zones(name, availability_zones, region=None, key=None, keyid=None, profile=None): ''' Disable availability zones for ELB. CLI example: .. code-block:: bash salt myminion boto_elb.disable_availability_zones myelb '["us-east-1a"]' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if isinstance(availability_zones, six.string_types): availability_zones = salt.utils.json.loads(availability_zones) try: conn.disable_availability_zones(name, availability_zones) log.info('Disabled availability_zones on ELB %s', name) return True except boto.exception.BotoServerError as error: log.error('Failed to disable availability_zones on ELB %s: %s', name, error, exc_info_on_loglevel=logging.DEBUG) return False def attach_subnets(name, subnets, region=None, key=None, keyid=None, profile=None): ''' Attach ELB to subnets. CLI example: .. code-block:: bash salt myminion boto_elb.attach_subnets myelb '["mysubnet"]' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if isinstance(subnets, six.string_types): subnets = salt.utils.json.loads(subnets) try: conn.attach_lb_to_subnets(name, subnets) log.info('Attached ELB %s on subnets.', name) return True except boto.exception.BotoServerError as error: log.error('Failed to attach ELB %s on subnets: %s', name, error, exc_info_on_loglevel=logging.DEBUG) return False def detach_subnets(name, subnets, region=None, key=None, keyid=None, profile=None): ''' Detach ELB from subnets. CLI example: .. code-block:: bash salt myminion boto_elb.detach_subnets myelb '["mysubnet"]' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if isinstance(subnets, six.string_types): subnets = salt.utils.json.loads(subnets) try: conn.detach_lb_from_subnets(name, subnets) log.info('Detached ELB %s from subnets.', name) return True except boto.exception.BotoServerError as error: log.error('Failed to detach ELB %s from subnets: %s', name, error, exc_info_on_loglevel=logging.DEBUG) return False def get_attributes(name, region=None, key=None, keyid=None, profile=None): ''' Check to see if attributes are set on an ELB. CLI example: .. code-block:: bash salt myminion boto_elb.get_attributes myelb ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) retries = 30 while retries: try: lbattrs = conn.get_all_lb_attributes(name) ret = odict.OrderedDict() ret['access_log'] = odict.OrderedDict() ret['cross_zone_load_balancing'] = odict.OrderedDict() ret['connection_draining'] = odict.OrderedDict() ret['connecting_settings'] = odict.OrderedDict() al = lbattrs.access_log czlb = lbattrs.cross_zone_load_balancing cd = lbattrs.connection_draining cs = lbattrs.connecting_settings ret['access_log']['enabled'] = al.enabled ret['access_log']['s3_bucket_name'] = al.s3_bucket_name ret['access_log']['s3_bucket_prefix'] = al.s3_bucket_prefix ret['access_log']['emit_interval'] = al.emit_interval ret['cross_zone_load_balancing']['enabled'] = czlb.enabled ret['connection_draining']['enabled'] = cd.enabled ret['connection_draining']['timeout'] = cd.timeout ret['connecting_settings']['idle_timeout'] = cs.idle_timeout return ret except boto.exception.BotoServerError as e: if e.error_code == 'Throttling': log.debug("Throttled by AWS API, will retry in 5 seconds...") time.sleep(5) retries -= 1 continue log.error('ELB %s does not exist: %s', name, e.message) return {} return {} def set_attributes(name, attributes, region=None, key=None, keyid=None, profile=None): ''' Set attributes on an ELB. name (string) Name of the ELB instance to set attributes for attributes A dict of attributes to set. Valid attributes are: access_log (dict) enabled (bool) Enable storage of access logs. s3_bucket_name (string) The name of the S3 bucket to place logs. s3_bucket_prefix (string) Prefix for the log file name. emit_interval (int) Interval for storing logs in S3 in minutes. Valid values are 5 and 60. connection_draining (dict) enabled (bool) Enable connection draining. timeout (int) Maximum allowed time in seconds for sending existing connections to an instance that is deregistering or unhealthy. Default is 300. cross_zone_load_balancing (dict) enabled (bool) Enable cross-zone load balancing. CLI example to set attributes on an ELB: .. code-block:: bash salt myminion boto_elb.set_attributes myelb '{"access_log": {"enabled": "true", "s3_bucket_name": "mybucket", "s3_bucket_prefix": "mylogs/", "emit_interval": "5"}}' region=us-east-1 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) al = attributes.get('access_log', {}) czlb = attributes.get('cross_zone_load_balancing', {}) cd = attributes.get('connection_draining', {}) cs = attributes.get('connecting_settings', {}) if not al and not czlb and not cd and not cs: log.error('No supported attributes for ELB.') return False if al: _al = AccessLogAttribute() _al.enabled = al.get('enabled', False) if not _al.enabled: msg = 'Access log attribute configured, but enabled config missing' log.error(msg) return False _al.s3_bucket_name = al.get('s3_bucket_name', None) _al.s3_bucket_prefix = al.get('s3_bucket_prefix', None) _al.emit_interval = al.get('emit_interval', None) added_attr = conn.modify_lb_attribute(name, 'accessLog', _al) if added_attr: log.info('Added access_log attribute to %s elb.', name) else: log.error('Failed to add access_log attribute to %s elb.', name) return False if czlb: _czlb = CrossZoneLoadBalancingAttribute() _czlb.enabled = czlb['enabled'] added_attr = conn.modify_lb_attribute(name, 'crossZoneLoadBalancing', _czlb.enabled) if added_attr: log.info('Added cross_zone_load_balancing attribute to %s elb.', name) else: log.error('Failed to add cross_zone_load_balancing attribute.') return False if cd: _cd = ConnectionDrainingAttribute() _cd.enabled = cd['enabled'] _cd.timeout = cd.get('timeout', 300) added_attr = conn.modify_lb_attribute(name, 'connectionDraining', _cd) if added_attr: log.info('Added connection_draining attribute to %s elb.', name) else: log.error('Failed to add connection_draining attribute.') return False if cs: _cs = ConnectionSettingAttribute() _cs.idle_timeout = cs.get('idle_timeout', 60) added_attr = conn.modify_lb_attribute(name, 'connectingSettings', _cs) if added_attr: log.info('Added connecting_settings attribute to %s elb.', name) else: log.error('Failed to add connecting_settings attribute.') return False return True def get_health_check(name, region=None, key=None, keyid=None, profile=None): ''' Get the health check configured for this ELB. CLI example: .. code-block:: bash salt myminion boto_elb.get_health_check myelb ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) retries = 30 while True: try: lb = conn.get_all_load_balancers(load_balancer_names=[name]) lb = lb[0] ret = odict.OrderedDict() hc = lb.health_check ret['interval'] = hc.interval ret['target'] = hc.target ret['healthy_threshold'] = hc.healthy_threshold ret['timeout'] = hc.timeout ret['unhealthy_threshold'] = hc.unhealthy_threshold return ret except boto.exception.BotoServerError as e: if retries and e.code == 'Throttling': log.debug('Throttled by AWS API, will retry in 5 seconds.') time.sleep(5) retries -= 1 continue log.error('ELB %s not found.', name, exc_info_on_logleve=logging.DEBUG) return {} def set_health_check(name, health_check, region=None, key=None, keyid=None, profile=None): ''' Set attributes on an ELB. CLI example to set attributes on an ELB: .. code-block:: bash salt myminion boto_elb.set_health_check myelb '{"target": "HTTP:80/"}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) retries = 30 hc = HealthCheck(**health_check) while True: try: conn.configure_health_check(name, hc) log.info('Configured health check on ELB %s', name) return True except boto.exception.BotoServerError as error: if retries and e.code == 'Throttling': log.debug('Throttled by AWS API, will retry in 5 seconds.') time.sleep(5) retries -= 1 continue log.exception('Failed to configure health check on ELB %s', name) return False def register_instances(name, instances, region=None, key=None, keyid=None, profile=None): ''' Register instances with an ELB. Instances is either a string instance id or a list of string instance id's. Returns: - ``True``: instance(s) registered successfully - ``False``: instance(s) failed to be registered CLI example: .. code-block:: bash salt myminion boto_elb.register_instances myelb instance_id salt myminion boto_elb.register_instances myelb "[instance_id,instance_id]" ''' # convert instances to list type, enabling consistent use of instances # variable throughout the register_instances method if isinstance(instances, six.string_types) or isinstance(instances, six.text_type): instances = [instances] conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: registered_instances = conn.register_instances(name, instances) except boto.exception.BotoServerError as error: log.warning(error) return False registered_instance_ids = [instance.id for instance in registered_instances] # register_failues is a set that will contain any instances that were not # able to be registered with the given ELB register_failures = set(instances).difference(set(registered_instance_ids)) if register_failures: log.warning('Instance(s): %s not registered with ELB %s.', list(register_failures), name) register_result = False else: register_result = True return register_result def deregister_instances(name, instances, region=None, key=None, keyid=None, profile=None): ''' Deregister instances with an ELB. Instances is either a string instance id or a list of string instance id's. Returns: - ``True``: instance(s) deregistered successfully - ``False``: instance(s) failed to be deregistered - ``None``: instance(s) not valid or not registered, no action taken CLI example: .. code-block:: bash salt myminion boto_elb.deregister_instances myelb instance_id salt myminion boto_elb.deregister_instances myelb "[instance_id, instance_id]" ''' # convert instances to list type, enabling consistent use of instances # variable throughout the deregister_instances method if isinstance(instances, six.string_types) or isinstance(instances, six.text_type): instances = [instances] conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: registered_instances = conn.deregister_instances(name, instances) except boto.exception.BotoServerError as error: # if the instance(s) given as an argument are not members of the ELB # boto returns error.error_code == 'InvalidInstance' # deregister_instances returns "None" because the instances are # effectively deregistered from ELB if error.error_code == 'InvalidInstance': log.warning( 'One or more of instance(s) %s are not part of ELB %s. ' 'deregister_instances not performed.', instances, name ) return None else: log.warning(error) return False registered_instance_ids = [instance.id for instance in registered_instances] # deregister_failures is a set that will contain any instances that were # unable to be deregistered from the given ELB deregister_failures = set(instances).intersection(set(registered_instance_ids)) if deregister_failures: log.warning( 'Instance(s): %s not deregistered from ELB %s.', list(deregister_failures), name ) deregister_result = False else: deregister_result = True return deregister_result def set_instances(name, instances, test=False, region=None, key=None, keyid=None, profile=None): ''' Set the instances assigned to an ELB to exactly the list given CLI example: .. code-block:: bash salt myminion boto_elb.set_instances myelb region=us-east-1 instances="[instance_id,instance_id]" ''' ret = True current = set([i['instance_id'] for i in get_instance_health(name, region, key, keyid, profile)]) desired = set(instances) add = desired - current remove = current - desired if test: return bool(add or remove) if remove: if deregister_instances(name, list(remove), region, key, keyid, profile) is False: ret = False if add: if register_instances(name, list(add), region, key, keyid, profile) is False: ret = False return ret def get_instance_health(name, region=None, key=None, keyid=None, profile=None, instances=None): ''' Get a list of instances and their health state CLI example: .. code-block:: bash salt myminion boto_elb.get_instance_health myelb salt myminion boto_elb.get_instance_health myelb region=us-east-1 instances="[instance_id,instance_id]" ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: instance_states = conn.describe_instance_health(name, instances) ret = [] for _instance in instance_states: ret.append({'instance_id': _instance.instance_id, 'description': _instance.description, 'state': _instance.state, 'reason_code': _instance.reason_code }) return ret except boto.exception.BotoServerError as error: log.debug(error) return [] def create_policy(name, policy_name, policy_type, policy, region=None, key=None, keyid=None, profile=None): ''' Create an ELB policy. .. versionadded:: 2016.3.0 CLI example: .. code-block:: bash salt myminion boto_elb.create_policy myelb mypolicy LBCookieStickinessPolicyType '{"CookieExpirationPeriod": 3600}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not exists(name, region, key, keyid, profile): return False try: success = conn.create_lb_policy(name, policy_name, policy_type, policy) if success: log.info('Created policy %s on ELB %s', policy_name, name) return True else: log.error('Failed to create policy %s on ELB %s', policy_name, name) return False except boto.exception.BotoServerError as e: log.error('Failed to create policy %s on ELB %s: %s', policy_name, name, e.message, exc_info_on_loglevel=logging.DEBUG) return False def delete_policy(name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Delete an ELB policy. .. versionadded:: 2016.3.0 CLI example: .. code-block:: bash salt myminion boto_elb.delete_policy myelb mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not exists(name, region, key, keyid, profile): return True try: conn.delete_lb_policy(name, policy_name) log.info('Deleted policy %s on ELB %s', policy_name, name) return True except boto.exception.BotoServerError as e: log.error('Failed to delete policy %s on ELB %s: %s', policy_name, name, e.message, exc_info_on_loglevel=logging.DEBUG) return False def set_listener_policy(name, port, policies=None, region=None, key=None, keyid=None, profile=None): ''' Set the policies of an ELB listener. .. versionadded:: 2016.3.0 CLI example: .. code-block:: Bash salt myminion boto_elb.set_listener_policy myelb 443 "[policy1,policy2]" ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not exists(name, region, key, keyid, profile): return True if policies is None: policies = [] try: conn.set_lb_policies_of_listener(name, port, policies) log.info('Set policies %s on ELB %s listener %s', policies, name, port) except boto.exception.BotoServerError as e: log.info('Failed to set policy %s on ELB %s listener %s: %s', policies, name, port, e.message, exc_info_on_loglevel=logging.DEBUG) return False return True def set_backend_policy(name, port, policies=None, region=None, key=None, keyid=None, profile=None): ''' Set the policies of an ELB backend server. CLI example: salt myminion boto_elb.set_backend_policy myelb 443 "[policy1,policy2]" ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not exists(name, region, key, keyid, profile): return True if policies is None: policies = [] try: conn.set_lb_policies_of_backend_server(name, port, policies) log.info('Set policies %s on ELB %s backend server %s', policies, name, port) except boto.exception.BotoServerError as e: log.info('Failed to set policy %s on ELB %s backend server %s: %s', policies, name, port, e.message, exc_info_on_loglevel=logging.DEBUG) return False return True def set_tags(name, tags, region=None, key=None, keyid=None, profile=None): ''' Add the tags on an ELB .. versionadded:: 2016.3.0 name name of the ELB tags dict of name/value pair tags CLI Example: .. code-block:: bash salt myminion boto_elb.set_tags my-elb-name "{'Tag1': 'Value', 'Tag2': 'Another Value'}" ''' if exists(name, region, key, keyid, profile): conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) ret = _add_tags(conn, name, tags) return ret else: return False def delete_tags(name, tags, region=None, key=None, keyid=None, profile=None): ''' Add the tags on an ELB name name of the ELB tags list of tags to remove CLI Example: .. code-block:: bash salt myminion boto_elb.delete_tags my-elb-name ['TagToRemove1', 'TagToRemove2'] ''' if exists(name, region, key, keyid, profile): conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) ret = _remove_tags(conn, name, tags) return ret else: return False def _build_tag_param_list(params, tags): ''' helper function to build a tag parameter list to send ''' keys = sorted(tags.keys()) i = 1 for key in keys: value = tags[key] params['Tags.member.{0}.Key'.format(i)] = key if value is not None: params['Tags.member.{0}.Value'.format(i)] = value i += 1 def _get_all_tags(conn, load_balancer_names=None): ''' Retrieve all the metadata tags associated with your ELB(s). :type load_balancer_names: list :param load_balancer_names: An optional list of load balancer names. :rtype: list :return: A list of :class:`boto.ec2.elb.tag.Tag` objects ''' params = {} if load_balancer_names: conn.build_list_params(params, load_balancer_names, 'LoadBalancerNames.member.%d') tags = conn.get_object( 'DescribeTags', params, __utils__['boto_elb_tag.get_tag_descriptions'](), verb='POST' ) if tags[load_balancer_names]: return tags[load_balancer_names] else: return None def _add_tags(conn, load_balancer_names, tags): ''' Create new metadata tags for the specified resource ids. :type load_balancer_names: list :param load_balancer_names: A list of load balancer names. :type tags: dict :param tags: A dictionary containing the name/value pairs. If you want to create only a tag name, the value for that tag should be the empty string (e.g. ''). ''' params = {} conn.build_list_params(params, load_balancer_names, 'LoadBalancerNames.member.%d') _build_tag_param_list(params, tags) return conn.get_status('AddTags', params, verb='POST') def _remove_tags(conn, load_balancer_names, tags): ''' Delete metadata tags for the specified resource ids. :type load_balancer_names: list :param load_balancer_names: A list of load balancer names. :type tags: list :param tags: A list containing just tag names for the tags to be deleted. ''' params = {} conn.build_list_params(params, load_balancer_names, 'LoadBalancerNames.member.%d') conn.build_list_params(params, tags, 'Tags.member.%d.Key') return conn.get_status('RemoveTags', params, verb='POST')
saltstack/salt
salt/modules/boto_elb.py
create_listeners
python
def create_listeners(name, listeners, region=None, key=None, keyid=None, profile=None): ''' Create listeners on an ELB. CLI example: .. code-block:: bash salt myminion boto_elb.create_listeners myelb '[["HTTPS", "HTTP", 443, 80, "arn:aws:iam::11 11111:server-certificate/mycert"]]' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if isinstance(listeners, six.string_types): listeners = salt.utils.json.loads(listeners) _complex_listeners = [] for listener in listeners: _complex_listeners.append(listener_dict_to_tuple(listener)) try: conn.create_load_balancer_listeners(name, [], _complex_listeners) log.info('Created ELB listeners on %s', name) return True except boto.exception.BotoServerError as error: log.error('Failed to create ELB listeners on %s: %s', name, error, exc_info_on_loglevel=logging.DEBUG) return False
Create listeners on an ELB. CLI example: .. code-block:: bash salt myminion boto_elb.create_listeners myelb '[["HTTPS", "HTTP", 443, 80, "arn:aws:iam::11 11111:server-certificate/mycert"]]'
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_elb.py#L303-L329
[ "def loads(s, **kwargs):\n '''\n .. versionadded:: 2018.3.0\n\n Wraps json.loads and prevents a traceback in the event that a bytestring is\n passed to the function. (Python < 3.6 cannot load bytestrings)\n\n You can pass an alternate json module (loaded via import_json() above)\n using the _json_module argument)\n '''\n json_module = kwargs.pop('_json_module', json)\n try:\n return json_module.loads(s, **kwargs)\n except TypeError as exc:\n # json.loads cannot load bytestrings in Python < 3.6\n if six.PY3 and isinstance(s, bytes):\n return json_module.loads(salt.utils.stringutils.to_unicode(s), **kwargs)\n else:\n raise exc\n", "def listener_dict_to_tuple(listener):\n '''\n Convert an ELB listener dict into a listener tuple used by certain parts of\n the AWS ELB API.\n\n CLI example:\n\n .. code-block:: bash\n\n salt myminion boto_elb.listener_dict_to_tuple '{\"elb_port\":80,\"instance_port\":80,\"elb_protocol\":\"HTTP\"}'\n '''\n # We define all listeners as complex listeners.\n if 'instance_protocol' not in listener:\n instance_protocol = listener['elb_protocol'].upper()\n else:\n instance_protocol = listener['instance_protocol'].upper()\n listener_tuple = [listener['elb_port'], listener['instance_port'],\n listener['elb_protocol'], instance_protocol]\n if 'certificate' in listener:\n listener_tuple.append(listener['certificate'])\n return tuple(listener_tuple)\n" ]
# -*- coding: utf-8 -*- ''' Connection module for Amazon ELB .. versionadded:: 2014.7.0 :configuration: This module accepts explicit elb credentials but can also utilize IAM roles assigned to the instance through Instance Profiles. Dynamic credentials are then automatically obtained from AWS API and no further configuration is necessary. More Information available at: .. code-block:: text http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/iam-roles-for-amazon-ec2.html If IAM roles are not used you need to specify them either in a pillar or in the minion's config file: .. code-block:: yaml elb.keyid: GKTADJGHEIQSXMKKRBJ08H elb.key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs A region may also be specified in the configuration: .. code-block:: yaml elb.region: us-east-1 If a region is not specified, the default is us-east-1. It's also possible to specify key, keyid and region via a profile, either as a passed in dict, or as a string to pull from pillars or minion config: .. code-block:: yaml myprofile: keyid: GKTADJGHEIQSXMKKRBJ08H key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs region: us-east-1 :depends: boto >= 2.33.0 ''' # keep lint from choking on _get_conn and _cache_id # pylint: disable=E0602 from __future__ import absolute_import, print_function, unicode_literals # Import Python libs import logging import time log = logging.getLogger(__name__) # Import Salt libs import salt.utils.json import salt.utils.odict as odict import salt.utils.versions # Import third party libs from salt.ext import six try: import boto import boto.ec2 # pylint: enable=unused-import from boto.ec2.elb import HealthCheck from boto.ec2.elb.attributes import AccessLogAttribute from boto.ec2.elb.attributes import ConnectionDrainingAttribute from boto.ec2.elb.attributes import ConnectionSettingAttribute from boto.ec2.elb.attributes import CrossZoneLoadBalancingAttribute logging.getLogger('boto').setLevel(logging.CRITICAL) HAS_BOTO = True except ImportError: HAS_BOTO = False def __virtual__(): ''' Only load if boto libraries exist. ''' # connection settings were added in 2.33.0 has_boto_reqs = salt.utils.versions.check_boto_reqs( boto_ver='2.33.0', check_boto3=False ) if has_boto_reqs is True: __utils__['boto.assign_funcs'](__name__, 'elb', module='ec2.elb', pack=__salt__) return has_boto_reqs def exists(name, region=None, key=None, keyid=None, profile=None): ''' Check to see if an ELB exists. CLI example: .. code-block:: bash salt myminion boto_elb.exists myelb region=us-east-1 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: elb = conn.get_all_load_balancers(load_balancer_names=[name]) if elb: return True else: log.debug('The load balancer does not exist in region %s', region) return False except boto.exception.BotoServerError as error: log.warning(error) return False def get_all_elbs(region=None, key=None, keyid=None, profile=None): ''' Return all load balancers associated with an account CLI example: .. code-block:: bash salt myminion boto_elb.get_all_elbs region=us-east-1 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: return [e for e in conn.get_all_load_balancers()] except boto.exception.BotoServerError as error: log.warning(error) return [] def list_elbs(region=None, key=None, keyid=None, profile=None): ''' Return names of all load balancers associated with an account CLI example: .. code-block:: bash salt myminion boto_elb.list_elbs region=us-east-1 ''' return [e.name for e in get_all_elbs(region=region, key=key, keyid=keyid, profile=profile)] def get_elb_config(name, region=None, key=None, keyid=None, profile=None): ''' Get an ELB configuration. CLI example: .. code-block:: bash salt myminion boto_elb.exists myelb region=us-east-1 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) retries = 30 while retries: try: lb = conn.get_all_load_balancers(load_balancer_names=[name]) lb = lb[0] ret = {} ret['availability_zones'] = lb.availability_zones listeners = [] for _listener in lb.listeners: listener_dict = {} listener_dict['elb_port'] = _listener.load_balancer_port listener_dict['elb_protocol'] = _listener.protocol listener_dict['instance_port'] = _listener.instance_port listener_dict['instance_protocol'] = _listener.instance_protocol listener_dict['policies'] = _listener.policy_names if _listener.ssl_certificate_id: listener_dict['certificate'] = _listener.ssl_certificate_id listeners.append(listener_dict) ret['listeners'] = listeners backends = [] for _backend in lb.backends: bs_dict = {} bs_dict['instance_port'] = _backend.instance_port bs_dict['policies'] = [p.policy_name for p in _backend.policies] backends.append(bs_dict) ret['backends'] = backends ret['subnets'] = lb.subnets ret['security_groups'] = lb.security_groups ret['scheme'] = lb.scheme ret['dns_name'] = lb.dns_name ret['tags'] = _get_all_tags(conn, name) lb_policy_lists = [ lb.policies.app_cookie_stickiness_policies, lb.policies.lb_cookie_stickiness_policies, lb.policies.other_policies ] policies = [] for policy_list in lb_policy_lists: policies += [p.policy_name for p in policy_list] ret['policies'] = policies return ret except boto.exception.BotoServerError as error: if error.error_code == 'Throttling': log.debug('Throttled by AWS API, will retry in 5 seconds.') time.sleep(5) retries -= 1 continue log.error('Error fetching config for ELB %s: %s', name, error.message) log.error(error) return {} return {} def listener_dict_to_tuple(listener): ''' Convert an ELB listener dict into a listener tuple used by certain parts of the AWS ELB API. CLI example: .. code-block:: bash salt myminion boto_elb.listener_dict_to_tuple '{"elb_port":80,"instance_port":80,"elb_protocol":"HTTP"}' ''' # We define all listeners as complex listeners. if 'instance_protocol' not in listener: instance_protocol = listener['elb_protocol'].upper() else: instance_protocol = listener['instance_protocol'].upper() listener_tuple = [listener['elb_port'], listener['instance_port'], listener['elb_protocol'], instance_protocol] if 'certificate' in listener: listener_tuple.append(listener['certificate']) return tuple(listener_tuple) def create(name, availability_zones, listeners, subnets=None, security_groups=None, scheme='internet-facing', region=None, key=None, keyid=None, profile=None): ''' Create an ELB CLI example to create an ELB: .. code-block:: bash salt myminion boto_elb.create myelb '["us-east-1a", "us-east-1e"]' '{"elb_port": 443, "elb_protocol": "HTTPS", ...}' region=us-east-1 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if exists(name, region, key, keyid, profile): return True if isinstance(availability_zones, six.string_types): availability_zones = salt.utils.json.loads(availability_zones) if isinstance(listeners, six.string_types): listeners = salt.utils.json.loads(listeners) _complex_listeners = [] for listener in listeners: _complex_listeners.append(listener_dict_to_tuple(listener)) try: lb = conn.create_load_balancer(name=name, zones=availability_zones, subnets=subnets, security_groups=security_groups, scheme=scheme, complex_listeners=_complex_listeners) if lb: log.info('Created ELB %s', name) return True else: log.error('Failed to create ELB %s', name) return False except boto.exception.BotoServerError as error: log.error('Failed to create ELB %s: %s: %s', name, error.error_code, error.message, exc_info_on_loglevel=logging.DEBUG) return False def delete(name, region=None, key=None, keyid=None, profile=None): ''' Delete an ELB. CLI example to delete an ELB: .. code-block:: bash salt myminion boto_elb.delete myelb region=us-east-1 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not exists(name, region, key, keyid, profile): return True try: conn.delete_load_balancer(name) log.info('Deleted ELB %s.', name) return True except boto.exception.BotoServerError as error: log.error('Failed to delete ELB %s', name, exc_info_on_loglevel=logging.DEBUG) return False def delete_listeners(name, ports, region=None, key=None, keyid=None, profile=None): ''' Delete listeners on an ELB. CLI example: .. code-block:: bash salt myminion boto_elb.delete_listeners myelb '[80,443]' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if isinstance(ports, six.string_types): ports = salt.utils.json.loads(ports) try: conn.delete_load_balancer_listeners(name, ports) log.info('Deleted ELB listeners on %s', name) return True except boto.exception.BotoServerError as error: log.error('Failed to delete ELB listeners on %s: %s', name, error, exc_info_on_loglevel=logging.DEBUG) return False def apply_security_groups(name, security_groups, region=None, key=None, keyid=None, profile=None): ''' Apply security groups to ELB. CLI example: .. code-block:: bash salt myminion boto_elb.apply_security_groups myelb '["mysecgroup1"]' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if isinstance(security_groups, six.string_types): security_groups = salt.utils.json.loads(security_groups) try: conn.apply_security_groups_to_lb(name, security_groups) log.info('Applied security_groups on ELB %s', name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to appply security_groups on ELB %s: %s', name, e.message) return False def enable_availability_zones(name, availability_zones, region=None, key=None, keyid=None, profile=None): ''' Enable availability zones for ELB. CLI example: .. code-block:: bash salt myminion boto_elb.enable_availability_zones myelb '["us-east-1a"]' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if isinstance(availability_zones, six.string_types): availability_zones = salt.utils.json.loads(availability_zones) try: conn.enable_availability_zones(name, availability_zones) log.info('Enabled availability_zones on ELB %s', name) return True except boto.exception.BotoServerError as error: log.error('Failed to enable availability_zones on ELB %s: %s', name, error) return False def disable_availability_zones(name, availability_zones, region=None, key=None, keyid=None, profile=None): ''' Disable availability zones for ELB. CLI example: .. code-block:: bash salt myminion boto_elb.disable_availability_zones myelb '["us-east-1a"]' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if isinstance(availability_zones, six.string_types): availability_zones = salt.utils.json.loads(availability_zones) try: conn.disable_availability_zones(name, availability_zones) log.info('Disabled availability_zones on ELB %s', name) return True except boto.exception.BotoServerError as error: log.error('Failed to disable availability_zones on ELB %s: %s', name, error, exc_info_on_loglevel=logging.DEBUG) return False def attach_subnets(name, subnets, region=None, key=None, keyid=None, profile=None): ''' Attach ELB to subnets. CLI example: .. code-block:: bash salt myminion boto_elb.attach_subnets myelb '["mysubnet"]' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if isinstance(subnets, six.string_types): subnets = salt.utils.json.loads(subnets) try: conn.attach_lb_to_subnets(name, subnets) log.info('Attached ELB %s on subnets.', name) return True except boto.exception.BotoServerError as error: log.error('Failed to attach ELB %s on subnets: %s', name, error, exc_info_on_loglevel=logging.DEBUG) return False def detach_subnets(name, subnets, region=None, key=None, keyid=None, profile=None): ''' Detach ELB from subnets. CLI example: .. code-block:: bash salt myminion boto_elb.detach_subnets myelb '["mysubnet"]' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if isinstance(subnets, six.string_types): subnets = salt.utils.json.loads(subnets) try: conn.detach_lb_from_subnets(name, subnets) log.info('Detached ELB %s from subnets.', name) return True except boto.exception.BotoServerError as error: log.error('Failed to detach ELB %s from subnets: %s', name, error, exc_info_on_loglevel=logging.DEBUG) return False def get_attributes(name, region=None, key=None, keyid=None, profile=None): ''' Check to see if attributes are set on an ELB. CLI example: .. code-block:: bash salt myminion boto_elb.get_attributes myelb ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) retries = 30 while retries: try: lbattrs = conn.get_all_lb_attributes(name) ret = odict.OrderedDict() ret['access_log'] = odict.OrderedDict() ret['cross_zone_load_balancing'] = odict.OrderedDict() ret['connection_draining'] = odict.OrderedDict() ret['connecting_settings'] = odict.OrderedDict() al = lbattrs.access_log czlb = lbattrs.cross_zone_load_balancing cd = lbattrs.connection_draining cs = lbattrs.connecting_settings ret['access_log']['enabled'] = al.enabled ret['access_log']['s3_bucket_name'] = al.s3_bucket_name ret['access_log']['s3_bucket_prefix'] = al.s3_bucket_prefix ret['access_log']['emit_interval'] = al.emit_interval ret['cross_zone_load_balancing']['enabled'] = czlb.enabled ret['connection_draining']['enabled'] = cd.enabled ret['connection_draining']['timeout'] = cd.timeout ret['connecting_settings']['idle_timeout'] = cs.idle_timeout return ret except boto.exception.BotoServerError as e: if e.error_code == 'Throttling': log.debug("Throttled by AWS API, will retry in 5 seconds...") time.sleep(5) retries -= 1 continue log.error('ELB %s does not exist: %s', name, e.message) return {} return {} def set_attributes(name, attributes, region=None, key=None, keyid=None, profile=None): ''' Set attributes on an ELB. name (string) Name of the ELB instance to set attributes for attributes A dict of attributes to set. Valid attributes are: access_log (dict) enabled (bool) Enable storage of access logs. s3_bucket_name (string) The name of the S3 bucket to place logs. s3_bucket_prefix (string) Prefix for the log file name. emit_interval (int) Interval for storing logs in S3 in minutes. Valid values are 5 and 60. connection_draining (dict) enabled (bool) Enable connection draining. timeout (int) Maximum allowed time in seconds for sending existing connections to an instance that is deregistering or unhealthy. Default is 300. cross_zone_load_balancing (dict) enabled (bool) Enable cross-zone load balancing. CLI example to set attributes on an ELB: .. code-block:: bash salt myminion boto_elb.set_attributes myelb '{"access_log": {"enabled": "true", "s3_bucket_name": "mybucket", "s3_bucket_prefix": "mylogs/", "emit_interval": "5"}}' region=us-east-1 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) al = attributes.get('access_log', {}) czlb = attributes.get('cross_zone_load_balancing', {}) cd = attributes.get('connection_draining', {}) cs = attributes.get('connecting_settings', {}) if not al and not czlb and not cd and not cs: log.error('No supported attributes for ELB.') return False if al: _al = AccessLogAttribute() _al.enabled = al.get('enabled', False) if not _al.enabled: msg = 'Access log attribute configured, but enabled config missing' log.error(msg) return False _al.s3_bucket_name = al.get('s3_bucket_name', None) _al.s3_bucket_prefix = al.get('s3_bucket_prefix', None) _al.emit_interval = al.get('emit_interval', None) added_attr = conn.modify_lb_attribute(name, 'accessLog', _al) if added_attr: log.info('Added access_log attribute to %s elb.', name) else: log.error('Failed to add access_log attribute to %s elb.', name) return False if czlb: _czlb = CrossZoneLoadBalancingAttribute() _czlb.enabled = czlb['enabled'] added_attr = conn.modify_lb_attribute(name, 'crossZoneLoadBalancing', _czlb.enabled) if added_attr: log.info('Added cross_zone_load_balancing attribute to %s elb.', name) else: log.error('Failed to add cross_zone_load_balancing attribute.') return False if cd: _cd = ConnectionDrainingAttribute() _cd.enabled = cd['enabled'] _cd.timeout = cd.get('timeout', 300) added_attr = conn.modify_lb_attribute(name, 'connectionDraining', _cd) if added_attr: log.info('Added connection_draining attribute to %s elb.', name) else: log.error('Failed to add connection_draining attribute.') return False if cs: _cs = ConnectionSettingAttribute() _cs.idle_timeout = cs.get('idle_timeout', 60) added_attr = conn.modify_lb_attribute(name, 'connectingSettings', _cs) if added_attr: log.info('Added connecting_settings attribute to %s elb.', name) else: log.error('Failed to add connecting_settings attribute.') return False return True def get_health_check(name, region=None, key=None, keyid=None, profile=None): ''' Get the health check configured for this ELB. CLI example: .. code-block:: bash salt myminion boto_elb.get_health_check myelb ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) retries = 30 while True: try: lb = conn.get_all_load_balancers(load_balancer_names=[name]) lb = lb[0] ret = odict.OrderedDict() hc = lb.health_check ret['interval'] = hc.interval ret['target'] = hc.target ret['healthy_threshold'] = hc.healthy_threshold ret['timeout'] = hc.timeout ret['unhealthy_threshold'] = hc.unhealthy_threshold return ret except boto.exception.BotoServerError as e: if retries and e.code == 'Throttling': log.debug('Throttled by AWS API, will retry in 5 seconds.') time.sleep(5) retries -= 1 continue log.error('ELB %s not found.', name, exc_info_on_logleve=logging.DEBUG) return {} def set_health_check(name, health_check, region=None, key=None, keyid=None, profile=None): ''' Set attributes on an ELB. CLI example to set attributes on an ELB: .. code-block:: bash salt myminion boto_elb.set_health_check myelb '{"target": "HTTP:80/"}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) retries = 30 hc = HealthCheck(**health_check) while True: try: conn.configure_health_check(name, hc) log.info('Configured health check on ELB %s', name) return True except boto.exception.BotoServerError as error: if retries and e.code == 'Throttling': log.debug('Throttled by AWS API, will retry in 5 seconds.') time.sleep(5) retries -= 1 continue log.exception('Failed to configure health check on ELB %s', name) return False def register_instances(name, instances, region=None, key=None, keyid=None, profile=None): ''' Register instances with an ELB. Instances is either a string instance id or a list of string instance id's. Returns: - ``True``: instance(s) registered successfully - ``False``: instance(s) failed to be registered CLI example: .. code-block:: bash salt myminion boto_elb.register_instances myelb instance_id salt myminion boto_elb.register_instances myelb "[instance_id,instance_id]" ''' # convert instances to list type, enabling consistent use of instances # variable throughout the register_instances method if isinstance(instances, six.string_types) or isinstance(instances, six.text_type): instances = [instances] conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: registered_instances = conn.register_instances(name, instances) except boto.exception.BotoServerError as error: log.warning(error) return False registered_instance_ids = [instance.id for instance in registered_instances] # register_failues is a set that will contain any instances that were not # able to be registered with the given ELB register_failures = set(instances).difference(set(registered_instance_ids)) if register_failures: log.warning('Instance(s): %s not registered with ELB %s.', list(register_failures), name) register_result = False else: register_result = True return register_result def deregister_instances(name, instances, region=None, key=None, keyid=None, profile=None): ''' Deregister instances with an ELB. Instances is either a string instance id or a list of string instance id's. Returns: - ``True``: instance(s) deregistered successfully - ``False``: instance(s) failed to be deregistered - ``None``: instance(s) not valid or not registered, no action taken CLI example: .. code-block:: bash salt myminion boto_elb.deregister_instances myelb instance_id salt myminion boto_elb.deregister_instances myelb "[instance_id, instance_id]" ''' # convert instances to list type, enabling consistent use of instances # variable throughout the deregister_instances method if isinstance(instances, six.string_types) or isinstance(instances, six.text_type): instances = [instances] conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: registered_instances = conn.deregister_instances(name, instances) except boto.exception.BotoServerError as error: # if the instance(s) given as an argument are not members of the ELB # boto returns error.error_code == 'InvalidInstance' # deregister_instances returns "None" because the instances are # effectively deregistered from ELB if error.error_code == 'InvalidInstance': log.warning( 'One or more of instance(s) %s are not part of ELB %s. ' 'deregister_instances not performed.', instances, name ) return None else: log.warning(error) return False registered_instance_ids = [instance.id for instance in registered_instances] # deregister_failures is a set that will contain any instances that were # unable to be deregistered from the given ELB deregister_failures = set(instances).intersection(set(registered_instance_ids)) if deregister_failures: log.warning( 'Instance(s): %s not deregistered from ELB %s.', list(deregister_failures), name ) deregister_result = False else: deregister_result = True return deregister_result def set_instances(name, instances, test=False, region=None, key=None, keyid=None, profile=None): ''' Set the instances assigned to an ELB to exactly the list given CLI example: .. code-block:: bash salt myminion boto_elb.set_instances myelb region=us-east-1 instances="[instance_id,instance_id]" ''' ret = True current = set([i['instance_id'] for i in get_instance_health(name, region, key, keyid, profile)]) desired = set(instances) add = desired - current remove = current - desired if test: return bool(add or remove) if remove: if deregister_instances(name, list(remove), region, key, keyid, profile) is False: ret = False if add: if register_instances(name, list(add), region, key, keyid, profile) is False: ret = False return ret def get_instance_health(name, region=None, key=None, keyid=None, profile=None, instances=None): ''' Get a list of instances and their health state CLI example: .. code-block:: bash salt myminion boto_elb.get_instance_health myelb salt myminion boto_elb.get_instance_health myelb region=us-east-1 instances="[instance_id,instance_id]" ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: instance_states = conn.describe_instance_health(name, instances) ret = [] for _instance in instance_states: ret.append({'instance_id': _instance.instance_id, 'description': _instance.description, 'state': _instance.state, 'reason_code': _instance.reason_code }) return ret except boto.exception.BotoServerError as error: log.debug(error) return [] def create_policy(name, policy_name, policy_type, policy, region=None, key=None, keyid=None, profile=None): ''' Create an ELB policy. .. versionadded:: 2016.3.0 CLI example: .. code-block:: bash salt myminion boto_elb.create_policy myelb mypolicy LBCookieStickinessPolicyType '{"CookieExpirationPeriod": 3600}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not exists(name, region, key, keyid, profile): return False try: success = conn.create_lb_policy(name, policy_name, policy_type, policy) if success: log.info('Created policy %s on ELB %s', policy_name, name) return True else: log.error('Failed to create policy %s on ELB %s', policy_name, name) return False except boto.exception.BotoServerError as e: log.error('Failed to create policy %s on ELB %s: %s', policy_name, name, e.message, exc_info_on_loglevel=logging.DEBUG) return False def delete_policy(name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Delete an ELB policy. .. versionadded:: 2016.3.0 CLI example: .. code-block:: bash salt myminion boto_elb.delete_policy myelb mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not exists(name, region, key, keyid, profile): return True try: conn.delete_lb_policy(name, policy_name) log.info('Deleted policy %s on ELB %s', policy_name, name) return True except boto.exception.BotoServerError as e: log.error('Failed to delete policy %s on ELB %s: %s', policy_name, name, e.message, exc_info_on_loglevel=logging.DEBUG) return False def set_listener_policy(name, port, policies=None, region=None, key=None, keyid=None, profile=None): ''' Set the policies of an ELB listener. .. versionadded:: 2016.3.0 CLI example: .. code-block:: Bash salt myminion boto_elb.set_listener_policy myelb 443 "[policy1,policy2]" ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not exists(name, region, key, keyid, profile): return True if policies is None: policies = [] try: conn.set_lb_policies_of_listener(name, port, policies) log.info('Set policies %s on ELB %s listener %s', policies, name, port) except boto.exception.BotoServerError as e: log.info('Failed to set policy %s on ELB %s listener %s: %s', policies, name, port, e.message, exc_info_on_loglevel=logging.DEBUG) return False return True def set_backend_policy(name, port, policies=None, region=None, key=None, keyid=None, profile=None): ''' Set the policies of an ELB backend server. CLI example: salt myminion boto_elb.set_backend_policy myelb 443 "[policy1,policy2]" ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not exists(name, region, key, keyid, profile): return True if policies is None: policies = [] try: conn.set_lb_policies_of_backend_server(name, port, policies) log.info('Set policies %s on ELB %s backend server %s', policies, name, port) except boto.exception.BotoServerError as e: log.info('Failed to set policy %s on ELB %s backend server %s: %s', policies, name, port, e.message, exc_info_on_loglevel=logging.DEBUG) return False return True def set_tags(name, tags, region=None, key=None, keyid=None, profile=None): ''' Add the tags on an ELB .. versionadded:: 2016.3.0 name name of the ELB tags dict of name/value pair tags CLI Example: .. code-block:: bash salt myminion boto_elb.set_tags my-elb-name "{'Tag1': 'Value', 'Tag2': 'Another Value'}" ''' if exists(name, region, key, keyid, profile): conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) ret = _add_tags(conn, name, tags) return ret else: return False def delete_tags(name, tags, region=None, key=None, keyid=None, profile=None): ''' Add the tags on an ELB name name of the ELB tags list of tags to remove CLI Example: .. code-block:: bash salt myminion boto_elb.delete_tags my-elb-name ['TagToRemove1', 'TagToRemove2'] ''' if exists(name, region, key, keyid, profile): conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) ret = _remove_tags(conn, name, tags) return ret else: return False def _build_tag_param_list(params, tags): ''' helper function to build a tag parameter list to send ''' keys = sorted(tags.keys()) i = 1 for key in keys: value = tags[key] params['Tags.member.{0}.Key'.format(i)] = key if value is not None: params['Tags.member.{0}.Value'.format(i)] = value i += 1 def _get_all_tags(conn, load_balancer_names=None): ''' Retrieve all the metadata tags associated with your ELB(s). :type load_balancer_names: list :param load_balancer_names: An optional list of load balancer names. :rtype: list :return: A list of :class:`boto.ec2.elb.tag.Tag` objects ''' params = {} if load_balancer_names: conn.build_list_params(params, load_balancer_names, 'LoadBalancerNames.member.%d') tags = conn.get_object( 'DescribeTags', params, __utils__['boto_elb_tag.get_tag_descriptions'](), verb='POST' ) if tags[load_balancer_names]: return tags[load_balancer_names] else: return None def _add_tags(conn, load_balancer_names, tags): ''' Create new metadata tags for the specified resource ids. :type load_balancer_names: list :param load_balancer_names: A list of load balancer names. :type tags: dict :param tags: A dictionary containing the name/value pairs. If you want to create only a tag name, the value for that tag should be the empty string (e.g. ''). ''' params = {} conn.build_list_params(params, load_balancer_names, 'LoadBalancerNames.member.%d') _build_tag_param_list(params, tags) return conn.get_status('AddTags', params, verb='POST') def _remove_tags(conn, load_balancer_names, tags): ''' Delete metadata tags for the specified resource ids. :type load_balancer_names: list :param load_balancer_names: A list of load balancer names. :type tags: list :param tags: A list containing just tag names for the tags to be deleted. ''' params = {} conn.build_list_params(params, load_balancer_names, 'LoadBalancerNames.member.%d') conn.build_list_params(params, tags, 'Tags.member.%d.Key') return conn.get_status('RemoveTags', params, verb='POST')
saltstack/salt
salt/modules/boto_elb.py
delete_listeners
python
def delete_listeners(name, ports, region=None, key=None, keyid=None, profile=None): ''' Delete listeners on an ELB. CLI example: .. code-block:: bash salt myminion boto_elb.delete_listeners myelb '[80,443]' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if isinstance(ports, six.string_types): ports = salt.utils.json.loads(ports) try: conn.delete_load_balancer_listeners(name, ports) log.info('Deleted ELB listeners on %s', name) return True except boto.exception.BotoServerError as error: log.error('Failed to delete ELB listeners on %s: %s', name, error, exc_info_on_loglevel=logging.DEBUG) return False
Delete listeners on an ELB. CLI example: .. code-block:: bash salt myminion boto_elb.delete_listeners myelb '[80,443]'
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_elb.py#L332-L354
[ "def loads(s, **kwargs):\n '''\n .. versionadded:: 2018.3.0\n\n Wraps json.loads and prevents a traceback in the event that a bytestring is\n passed to the function. (Python < 3.6 cannot load bytestrings)\n\n You can pass an alternate json module (loaded via import_json() above)\n using the _json_module argument)\n '''\n json_module = kwargs.pop('_json_module', json)\n try:\n return json_module.loads(s, **kwargs)\n except TypeError as exc:\n # json.loads cannot load bytestrings in Python < 3.6\n if six.PY3 and isinstance(s, bytes):\n return json_module.loads(salt.utils.stringutils.to_unicode(s), **kwargs)\n else:\n raise exc\n" ]
# -*- coding: utf-8 -*- ''' Connection module for Amazon ELB .. versionadded:: 2014.7.0 :configuration: This module accepts explicit elb credentials but can also utilize IAM roles assigned to the instance through Instance Profiles. Dynamic credentials are then automatically obtained from AWS API and no further configuration is necessary. More Information available at: .. code-block:: text http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/iam-roles-for-amazon-ec2.html If IAM roles are not used you need to specify them either in a pillar or in the minion's config file: .. code-block:: yaml elb.keyid: GKTADJGHEIQSXMKKRBJ08H elb.key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs A region may also be specified in the configuration: .. code-block:: yaml elb.region: us-east-1 If a region is not specified, the default is us-east-1. It's also possible to specify key, keyid and region via a profile, either as a passed in dict, or as a string to pull from pillars or minion config: .. code-block:: yaml myprofile: keyid: GKTADJGHEIQSXMKKRBJ08H key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs region: us-east-1 :depends: boto >= 2.33.0 ''' # keep lint from choking on _get_conn and _cache_id # pylint: disable=E0602 from __future__ import absolute_import, print_function, unicode_literals # Import Python libs import logging import time log = logging.getLogger(__name__) # Import Salt libs import salt.utils.json import salt.utils.odict as odict import salt.utils.versions # Import third party libs from salt.ext import six try: import boto import boto.ec2 # pylint: enable=unused-import from boto.ec2.elb import HealthCheck from boto.ec2.elb.attributes import AccessLogAttribute from boto.ec2.elb.attributes import ConnectionDrainingAttribute from boto.ec2.elb.attributes import ConnectionSettingAttribute from boto.ec2.elb.attributes import CrossZoneLoadBalancingAttribute logging.getLogger('boto').setLevel(logging.CRITICAL) HAS_BOTO = True except ImportError: HAS_BOTO = False def __virtual__(): ''' Only load if boto libraries exist. ''' # connection settings were added in 2.33.0 has_boto_reqs = salt.utils.versions.check_boto_reqs( boto_ver='2.33.0', check_boto3=False ) if has_boto_reqs is True: __utils__['boto.assign_funcs'](__name__, 'elb', module='ec2.elb', pack=__salt__) return has_boto_reqs def exists(name, region=None, key=None, keyid=None, profile=None): ''' Check to see if an ELB exists. CLI example: .. code-block:: bash salt myminion boto_elb.exists myelb region=us-east-1 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: elb = conn.get_all_load_balancers(load_balancer_names=[name]) if elb: return True else: log.debug('The load balancer does not exist in region %s', region) return False except boto.exception.BotoServerError as error: log.warning(error) return False def get_all_elbs(region=None, key=None, keyid=None, profile=None): ''' Return all load balancers associated with an account CLI example: .. code-block:: bash salt myminion boto_elb.get_all_elbs region=us-east-1 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: return [e for e in conn.get_all_load_balancers()] except boto.exception.BotoServerError as error: log.warning(error) return [] def list_elbs(region=None, key=None, keyid=None, profile=None): ''' Return names of all load balancers associated with an account CLI example: .. code-block:: bash salt myminion boto_elb.list_elbs region=us-east-1 ''' return [e.name for e in get_all_elbs(region=region, key=key, keyid=keyid, profile=profile)] def get_elb_config(name, region=None, key=None, keyid=None, profile=None): ''' Get an ELB configuration. CLI example: .. code-block:: bash salt myminion boto_elb.exists myelb region=us-east-1 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) retries = 30 while retries: try: lb = conn.get_all_load_balancers(load_balancer_names=[name]) lb = lb[0] ret = {} ret['availability_zones'] = lb.availability_zones listeners = [] for _listener in lb.listeners: listener_dict = {} listener_dict['elb_port'] = _listener.load_balancer_port listener_dict['elb_protocol'] = _listener.protocol listener_dict['instance_port'] = _listener.instance_port listener_dict['instance_protocol'] = _listener.instance_protocol listener_dict['policies'] = _listener.policy_names if _listener.ssl_certificate_id: listener_dict['certificate'] = _listener.ssl_certificate_id listeners.append(listener_dict) ret['listeners'] = listeners backends = [] for _backend in lb.backends: bs_dict = {} bs_dict['instance_port'] = _backend.instance_port bs_dict['policies'] = [p.policy_name for p in _backend.policies] backends.append(bs_dict) ret['backends'] = backends ret['subnets'] = lb.subnets ret['security_groups'] = lb.security_groups ret['scheme'] = lb.scheme ret['dns_name'] = lb.dns_name ret['tags'] = _get_all_tags(conn, name) lb_policy_lists = [ lb.policies.app_cookie_stickiness_policies, lb.policies.lb_cookie_stickiness_policies, lb.policies.other_policies ] policies = [] for policy_list in lb_policy_lists: policies += [p.policy_name for p in policy_list] ret['policies'] = policies return ret except boto.exception.BotoServerError as error: if error.error_code == 'Throttling': log.debug('Throttled by AWS API, will retry in 5 seconds.') time.sleep(5) retries -= 1 continue log.error('Error fetching config for ELB %s: %s', name, error.message) log.error(error) return {} return {} def listener_dict_to_tuple(listener): ''' Convert an ELB listener dict into a listener tuple used by certain parts of the AWS ELB API. CLI example: .. code-block:: bash salt myminion boto_elb.listener_dict_to_tuple '{"elb_port":80,"instance_port":80,"elb_protocol":"HTTP"}' ''' # We define all listeners as complex listeners. if 'instance_protocol' not in listener: instance_protocol = listener['elb_protocol'].upper() else: instance_protocol = listener['instance_protocol'].upper() listener_tuple = [listener['elb_port'], listener['instance_port'], listener['elb_protocol'], instance_protocol] if 'certificate' in listener: listener_tuple.append(listener['certificate']) return tuple(listener_tuple) def create(name, availability_zones, listeners, subnets=None, security_groups=None, scheme='internet-facing', region=None, key=None, keyid=None, profile=None): ''' Create an ELB CLI example to create an ELB: .. code-block:: bash salt myminion boto_elb.create myelb '["us-east-1a", "us-east-1e"]' '{"elb_port": 443, "elb_protocol": "HTTPS", ...}' region=us-east-1 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if exists(name, region, key, keyid, profile): return True if isinstance(availability_zones, six.string_types): availability_zones = salt.utils.json.loads(availability_zones) if isinstance(listeners, six.string_types): listeners = salt.utils.json.loads(listeners) _complex_listeners = [] for listener in listeners: _complex_listeners.append(listener_dict_to_tuple(listener)) try: lb = conn.create_load_balancer(name=name, zones=availability_zones, subnets=subnets, security_groups=security_groups, scheme=scheme, complex_listeners=_complex_listeners) if lb: log.info('Created ELB %s', name) return True else: log.error('Failed to create ELB %s', name) return False except boto.exception.BotoServerError as error: log.error('Failed to create ELB %s: %s: %s', name, error.error_code, error.message, exc_info_on_loglevel=logging.DEBUG) return False def delete(name, region=None, key=None, keyid=None, profile=None): ''' Delete an ELB. CLI example to delete an ELB: .. code-block:: bash salt myminion boto_elb.delete myelb region=us-east-1 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not exists(name, region, key, keyid, profile): return True try: conn.delete_load_balancer(name) log.info('Deleted ELB %s.', name) return True except boto.exception.BotoServerError as error: log.error('Failed to delete ELB %s', name, exc_info_on_loglevel=logging.DEBUG) return False def create_listeners(name, listeners, region=None, key=None, keyid=None, profile=None): ''' Create listeners on an ELB. CLI example: .. code-block:: bash salt myminion boto_elb.create_listeners myelb '[["HTTPS", "HTTP", 443, 80, "arn:aws:iam::11 11111:server-certificate/mycert"]]' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if isinstance(listeners, six.string_types): listeners = salt.utils.json.loads(listeners) _complex_listeners = [] for listener in listeners: _complex_listeners.append(listener_dict_to_tuple(listener)) try: conn.create_load_balancer_listeners(name, [], _complex_listeners) log.info('Created ELB listeners on %s', name) return True except boto.exception.BotoServerError as error: log.error('Failed to create ELB listeners on %s: %s', name, error, exc_info_on_loglevel=logging.DEBUG) return False def apply_security_groups(name, security_groups, region=None, key=None, keyid=None, profile=None): ''' Apply security groups to ELB. CLI example: .. code-block:: bash salt myminion boto_elb.apply_security_groups myelb '["mysecgroup1"]' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if isinstance(security_groups, six.string_types): security_groups = salt.utils.json.loads(security_groups) try: conn.apply_security_groups_to_lb(name, security_groups) log.info('Applied security_groups on ELB %s', name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to appply security_groups on ELB %s: %s', name, e.message) return False def enable_availability_zones(name, availability_zones, region=None, key=None, keyid=None, profile=None): ''' Enable availability zones for ELB. CLI example: .. code-block:: bash salt myminion boto_elb.enable_availability_zones myelb '["us-east-1a"]' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if isinstance(availability_zones, six.string_types): availability_zones = salt.utils.json.loads(availability_zones) try: conn.enable_availability_zones(name, availability_zones) log.info('Enabled availability_zones on ELB %s', name) return True except boto.exception.BotoServerError as error: log.error('Failed to enable availability_zones on ELB %s: %s', name, error) return False def disable_availability_zones(name, availability_zones, region=None, key=None, keyid=None, profile=None): ''' Disable availability zones for ELB. CLI example: .. code-block:: bash salt myminion boto_elb.disable_availability_zones myelb '["us-east-1a"]' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if isinstance(availability_zones, six.string_types): availability_zones = salt.utils.json.loads(availability_zones) try: conn.disable_availability_zones(name, availability_zones) log.info('Disabled availability_zones on ELB %s', name) return True except boto.exception.BotoServerError as error: log.error('Failed to disable availability_zones on ELB %s: %s', name, error, exc_info_on_loglevel=logging.DEBUG) return False def attach_subnets(name, subnets, region=None, key=None, keyid=None, profile=None): ''' Attach ELB to subnets. CLI example: .. code-block:: bash salt myminion boto_elb.attach_subnets myelb '["mysubnet"]' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if isinstance(subnets, six.string_types): subnets = salt.utils.json.loads(subnets) try: conn.attach_lb_to_subnets(name, subnets) log.info('Attached ELB %s on subnets.', name) return True except boto.exception.BotoServerError as error: log.error('Failed to attach ELB %s on subnets: %s', name, error, exc_info_on_loglevel=logging.DEBUG) return False def detach_subnets(name, subnets, region=None, key=None, keyid=None, profile=None): ''' Detach ELB from subnets. CLI example: .. code-block:: bash salt myminion boto_elb.detach_subnets myelb '["mysubnet"]' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if isinstance(subnets, six.string_types): subnets = salt.utils.json.loads(subnets) try: conn.detach_lb_from_subnets(name, subnets) log.info('Detached ELB %s from subnets.', name) return True except boto.exception.BotoServerError as error: log.error('Failed to detach ELB %s from subnets: %s', name, error, exc_info_on_loglevel=logging.DEBUG) return False def get_attributes(name, region=None, key=None, keyid=None, profile=None): ''' Check to see if attributes are set on an ELB. CLI example: .. code-block:: bash salt myminion boto_elb.get_attributes myelb ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) retries = 30 while retries: try: lbattrs = conn.get_all_lb_attributes(name) ret = odict.OrderedDict() ret['access_log'] = odict.OrderedDict() ret['cross_zone_load_balancing'] = odict.OrderedDict() ret['connection_draining'] = odict.OrderedDict() ret['connecting_settings'] = odict.OrderedDict() al = lbattrs.access_log czlb = lbattrs.cross_zone_load_balancing cd = lbattrs.connection_draining cs = lbattrs.connecting_settings ret['access_log']['enabled'] = al.enabled ret['access_log']['s3_bucket_name'] = al.s3_bucket_name ret['access_log']['s3_bucket_prefix'] = al.s3_bucket_prefix ret['access_log']['emit_interval'] = al.emit_interval ret['cross_zone_load_balancing']['enabled'] = czlb.enabled ret['connection_draining']['enabled'] = cd.enabled ret['connection_draining']['timeout'] = cd.timeout ret['connecting_settings']['idle_timeout'] = cs.idle_timeout return ret except boto.exception.BotoServerError as e: if e.error_code == 'Throttling': log.debug("Throttled by AWS API, will retry in 5 seconds...") time.sleep(5) retries -= 1 continue log.error('ELB %s does not exist: %s', name, e.message) return {} return {} def set_attributes(name, attributes, region=None, key=None, keyid=None, profile=None): ''' Set attributes on an ELB. name (string) Name of the ELB instance to set attributes for attributes A dict of attributes to set. Valid attributes are: access_log (dict) enabled (bool) Enable storage of access logs. s3_bucket_name (string) The name of the S3 bucket to place logs. s3_bucket_prefix (string) Prefix for the log file name. emit_interval (int) Interval for storing logs in S3 in minutes. Valid values are 5 and 60. connection_draining (dict) enabled (bool) Enable connection draining. timeout (int) Maximum allowed time in seconds for sending existing connections to an instance that is deregistering or unhealthy. Default is 300. cross_zone_load_balancing (dict) enabled (bool) Enable cross-zone load balancing. CLI example to set attributes on an ELB: .. code-block:: bash salt myminion boto_elb.set_attributes myelb '{"access_log": {"enabled": "true", "s3_bucket_name": "mybucket", "s3_bucket_prefix": "mylogs/", "emit_interval": "5"}}' region=us-east-1 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) al = attributes.get('access_log', {}) czlb = attributes.get('cross_zone_load_balancing', {}) cd = attributes.get('connection_draining', {}) cs = attributes.get('connecting_settings', {}) if not al and not czlb and not cd and not cs: log.error('No supported attributes for ELB.') return False if al: _al = AccessLogAttribute() _al.enabled = al.get('enabled', False) if not _al.enabled: msg = 'Access log attribute configured, but enabled config missing' log.error(msg) return False _al.s3_bucket_name = al.get('s3_bucket_name', None) _al.s3_bucket_prefix = al.get('s3_bucket_prefix', None) _al.emit_interval = al.get('emit_interval', None) added_attr = conn.modify_lb_attribute(name, 'accessLog', _al) if added_attr: log.info('Added access_log attribute to %s elb.', name) else: log.error('Failed to add access_log attribute to %s elb.', name) return False if czlb: _czlb = CrossZoneLoadBalancingAttribute() _czlb.enabled = czlb['enabled'] added_attr = conn.modify_lb_attribute(name, 'crossZoneLoadBalancing', _czlb.enabled) if added_attr: log.info('Added cross_zone_load_balancing attribute to %s elb.', name) else: log.error('Failed to add cross_zone_load_balancing attribute.') return False if cd: _cd = ConnectionDrainingAttribute() _cd.enabled = cd['enabled'] _cd.timeout = cd.get('timeout', 300) added_attr = conn.modify_lb_attribute(name, 'connectionDraining', _cd) if added_attr: log.info('Added connection_draining attribute to %s elb.', name) else: log.error('Failed to add connection_draining attribute.') return False if cs: _cs = ConnectionSettingAttribute() _cs.idle_timeout = cs.get('idle_timeout', 60) added_attr = conn.modify_lb_attribute(name, 'connectingSettings', _cs) if added_attr: log.info('Added connecting_settings attribute to %s elb.', name) else: log.error('Failed to add connecting_settings attribute.') return False return True def get_health_check(name, region=None, key=None, keyid=None, profile=None): ''' Get the health check configured for this ELB. CLI example: .. code-block:: bash salt myminion boto_elb.get_health_check myelb ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) retries = 30 while True: try: lb = conn.get_all_load_balancers(load_balancer_names=[name]) lb = lb[0] ret = odict.OrderedDict() hc = lb.health_check ret['interval'] = hc.interval ret['target'] = hc.target ret['healthy_threshold'] = hc.healthy_threshold ret['timeout'] = hc.timeout ret['unhealthy_threshold'] = hc.unhealthy_threshold return ret except boto.exception.BotoServerError as e: if retries and e.code == 'Throttling': log.debug('Throttled by AWS API, will retry in 5 seconds.') time.sleep(5) retries -= 1 continue log.error('ELB %s not found.', name, exc_info_on_logleve=logging.DEBUG) return {} def set_health_check(name, health_check, region=None, key=None, keyid=None, profile=None): ''' Set attributes on an ELB. CLI example to set attributes on an ELB: .. code-block:: bash salt myminion boto_elb.set_health_check myelb '{"target": "HTTP:80/"}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) retries = 30 hc = HealthCheck(**health_check) while True: try: conn.configure_health_check(name, hc) log.info('Configured health check on ELB %s', name) return True except boto.exception.BotoServerError as error: if retries and e.code == 'Throttling': log.debug('Throttled by AWS API, will retry in 5 seconds.') time.sleep(5) retries -= 1 continue log.exception('Failed to configure health check on ELB %s', name) return False def register_instances(name, instances, region=None, key=None, keyid=None, profile=None): ''' Register instances with an ELB. Instances is either a string instance id or a list of string instance id's. Returns: - ``True``: instance(s) registered successfully - ``False``: instance(s) failed to be registered CLI example: .. code-block:: bash salt myminion boto_elb.register_instances myelb instance_id salt myminion boto_elb.register_instances myelb "[instance_id,instance_id]" ''' # convert instances to list type, enabling consistent use of instances # variable throughout the register_instances method if isinstance(instances, six.string_types) or isinstance(instances, six.text_type): instances = [instances] conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: registered_instances = conn.register_instances(name, instances) except boto.exception.BotoServerError as error: log.warning(error) return False registered_instance_ids = [instance.id for instance in registered_instances] # register_failues is a set that will contain any instances that were not # able to be registered with the given ELB register_failures = set(instances).difference(set(registered_instance_ids)) if register_failures: log.warning('Instance(s): %s not registered with ELB %s.', list(register_failures), name) register_result = False else: register_result = True return register_result def deregister_instances(name, instances, region=None, key=None, keyid=None, profile=None): ''' Deregister instances with an ELB. Instances is either a string instance id or a list of string instance id's. Returns: - ``True``: instance(s) deregistered successfully - ``False``: instance(s) failed to be deregistered - ``None``: instance(s) not valid or not registered, no action taken CLI example: .. code-block:: bash salt myminion boto_elb.deregister_instances myelb instance_id salt myminion boto_elb.deregister_instances myelb "[instance_id, instance_id]" ''' # convert instances to list type, enabling consistent use of instances # variable throughout the deregister_instances method if isinstance(instances, six.string_types) or isinstance(instances, six.text_type): instances = [instances] conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: registered_instances = conn.deregister_instances(name, instances) except boto.exception.BotoServerError as error: # if the instance(s) given as an argument are not members of the ELB # boto returns error.error_code == 'InvalidInstance' # deregister_instances returns "None" because the instances are # effectively deregistered from ELB if error.error_code == 'InvalidInstance': log.warning( 'One or more of instance(s) %s are not part of ELB %s. ' 'deregister_instances not performed.', instances, name ) return None else: log.warning(error) return False registered_instance_ids = [instance.id for instance in registered_instances] # deregister_failures is a set that will contain any instances that were # unable to be deregistered from the given ELB deregister_failures = set(instances).intersection(set(registered_instance_ids)) if deregister_failures: log.warning( 'Instance(s): %s not deregistered from ELB %s.', list(deregister_failures), name ) deregister_result = False else: deregister_result = True return deregister_result def set_instances(name, instances, test=False, region=None, key=None, keyid=None, profile=None): ''' Set the instances assigned to an ELB to exactly the list given CLI example: .. code-block:: bash salt myminion boto_elb.set_instances myelb region=us-east-1 instances="[instance_id,instance_id]" ''' ret = True current = set([i['instance_id'] for i in get_instance_health(name, region, key, keyid, profile)]) desired = set(instances) add = desired - current remove = current - desired if test: return bool(add or remove) if remove: if deregister_instances(name, list(remove), region, key, keyid, profile) is False: ret = False if add: if register_instances(name, list(add), region, key, keyid, profile) is False: ret = False return ret def get_instance_health(name, region=None, key=None, keyid=None, profile=None, instances=None): ''' Get a list of instances and their health state CLI example: .. code-block:: bash salt myminion boto_elb.get_instance_health myelb salt myminion boto_elb.get_instance_health myelb region=us-east-1 instances="[instance_id,instance_id]" ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: instance_states = conn.describe_instance_health(name, instances) ret = [] for _instance in instance_states: ret.append({'instance_id': _instance.instance_id, 'description': _instance.description, 'state': _instance.state, 'reason_code': _instance.reason_code }) return ret except boto.exception.BotoServerError as error: log.debug(error) return [] def create_policy(name, policy_name, policy_type, policy, region=None, key=None, keyid=None, profile=None): ''' Create an ELB policy. .. versionadded:: 2016.3.0 CLI example: .. code-block:: bash salt myminion boto_elb.create_policy myelb mypolicy LBCookieStickinessPolicyType '{"CookieExpirationPeriod": 3600}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not exists(name, region, key, keyid, profile): return False try: success = conn.create_lb_policy(name, policy_name, policy_type, policy) if success: log.info('Created policy %s on ELB %s', policy_name, name) return True else: log.error('Failed to create policy %s on ELB %s', policy_name, name) return False except boto.exception.BotoServerError as e: log.error('Failed to create policy %s on ELB %s: %s', policy_name, name, e.message, exc_info_on_loglevel=logging.DEBUG) return False def delete_policy(name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Delete an ELB policy. .. versionadded:: 2016.3.0 CLI example: .. code-block:: bash salt myminion boto_elb.delete_policy myelb mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not exists(name, region, key, keyid, profile): return True try: conn.delete_lb_policy(name, policy_name) log.info('Deleted policy %s on ELB %s', policy_name, name) return True except boto.exception.BotoServerError as e: log.error('Failed to delete policy %s on ELB %s: %s', policy_name, name, e.message, exc_info_on_loglevel=logging.DEBUG) return False def set_listener_policy(name, port, policies=None, region=None, key=None, keyid=None, profile=None): ''' Set the policies of an ELB listener. .. versionadded:: 2016.3.0 CLI example: .. code-block:: Bash salt myminion boto_elb.set_listener_policy myelb 443 "[policy1,policy2]" ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not exists(name, region, key, keyid, profile): return True if policies is None: policies = [] try: conn.set_lb_policies_of_listener(name, port, policies) log.info('Set policies %s on ELB %s listener %s', policies, name, port) except boto.exception.BotoServerError as e: log.info('Failed to set policy %s on ELB %s listener %s: %s', policies, name, port, e.message, exc_info_on_loglevel=logging.DEBUG) return False return True def set_backend_policy(name, port, policies=None, region=None, key=None, keyid=None, profile=None): ''' Set the policies of an ELB backend server. CLI example: salt myminion boto_elb.set_backend_policy myelb 443 "[policy1,policy2]" ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not exists(name, region, key, keyid, profile): return True if policies is None: policies = [] try: conn.set_lb_policies_of_backend_server(name, port, policies) log.info('Set policies %s on ELB %s backend server %s', policies, name, port) except boto.exception.BotoServerError as e: log.info('Failed to set policy %s on ELB %s backend server %s: %s', policies, name, port, e.message, exc_info_on_loglevel=logging.DEBUG) return False return True def set_tags(name, tags, region=None, key=None, keyid=None, profile=None): ''' Add the tags on an ELB .. versionadded:: 2016.3.0 name name of the ELB tags dict of name/value pair tags CLI Example: .. code-block:: bash salt myminion boto_elb.set_tags my-elb-name "{'Tag1': 'Value', 'Tag2': 'Another Value'}" ''' if exists(name, region, key, keyid, profile): conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) ret = _add_tags(conn, name, tags) return ret else: return False def delete_tags(name, tags, region=None, key=None, keyid=None, profile=None): ''' Add the tags on an ELB name name of the ELB tags list of tags to remove CLI Example: .. code-block:: bash salt myminion boto_elb.delete_tags my-elb-name ['TagToRemove1', 'TagToRemove2'] ''' if exists(name, region, key, keyid, profile): conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) ret = _remove_tags(conn, name, tags) return ret else: return False def _build_tag_param_list(params, tags): ''' helper function to build a tag parameter list to send ''' keys = sorted(tags.keys()) i = 1 for key in keys: value = tags[key] params['Tags.member.{0}.Key'.format(i)] = key if value is not None: params['Tags.member.{0}.Value'.format(i)] = value i += 1 def _get_all_tags(conn, load_balancer_names=None): ''' Retrieve all the metadata tags associated with your ELB(s). :type load_balancer_names: list :param load_balancer_names: An optional list of load balancer names. :rtype: list :return: A list of :class:`boto.ec2.elb.tag.Tag` objects ''' params = {} if load_balancer_names: conn.build_list_params(params, load_balancer_names, 'LoadBalancerNames.member.%d') tags = conn.get_object( 'DescribeTags', params, __utils__['boto_elb_tag.get_tag_descriptions'](), verb='POST' ) if tags[load_balancer_names]: return tags[load_balancer_names] else: return None def _add_tags(conn, load_balancer_names, tags): ''' Create new metadata tags for the specified resource ids. :type load_balancer_names: list :param load_balancer_names: A list of load balancer names. :type tags: dict :param tags: A dictionary containing the name/value pairs. If you want to create only a tag name, the value for that tag should be the empty string (e.g. ''). ''' params = {} conn.build_list_params(params, load_balancer_names, 'LoadBalancerNames.member.%d') _build_tag_param_list(params, tags) return conn.get_status('AddTags', params, verb='POST') def _remove_tags(conn, load_balancer_names, tags): ''' Delete metadata tags for the specified resource ids. :type load_balancer_names: list :param load_balancer_names: A list of load balancer names. :type tags: list :param tags: A list containing just tag names for the tags to be deleted. ''' params = {} conn.build_list_params(params, load_balancer_names, 'LoadBalancerNames.member.%d') conn.build_list_params(params, tags, 'Tags.member.%d.Key') return conn.get_status('RemoveTags', params, verb='POST')
saltstack/salt
salt/modules/boto_elb.py
apply_security_groups
python
def apply_security_groups(name, security_groups, region=None, key=None, keyid=None, profile=None): ''' Apply security groups to ELB. CLI example: .. code-block:: bash salt myminion boto_elb.apply_security_groups myelb '["mysecgroup1"]' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if isinstance(security_groups, six.string_types): security_groups = salt.utils.json.loads(security_groups) try: conn.apply_security_groups_to_lb(name, security_groups) log.info('Applied security_groups on ELB %s', name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to appply security_groups on ELB %s: %s', name, e.message) return False
Apply security groups to ELB. CLI example: .. code-block:: bash salt myminion boto_elb.apply_security_groups myelb '["mysecgroup1"]'
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_elb.py#L357-L380
[ "def loads(s, **kwargs):\n '''\n .. versionadded:: 2018.3.0\n\n Wraps json.loads and prevents a traceback in the event that a bytestring is\n passed to the function. (Python < 3.6 cannot load bytestrings)\n\n You can pass an alternate json module (loaded via import_json() above)\n using the _json_module argument)\n '''\n json_module = kwargs.pop('_json_module', json)\n try:\n return json_module.loads(s, **kwargs)\n except TypeError as exc:\n # json.loads cannot load bytestrings in Python < 3.6\n if six.PY3 and isinstance(s, bytes):\n return json_module.loads(salt.utils.stringutils.to_unicode(s), **kwargs)\n else:\n raise exc\n" ]
# -*- coding: utf-8 -*- ''' Connection module for Amazon ELB .. versionadded:: 2014.7.0 :configuration: This module accepts explicit elb credentials but can also utilize IAM roles assigned to the instance through Instance Profiles. Dynamic credentials are then automatically obtained from AWS API and no further configuration is necessary. More Information available at: .. code-block:: text http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/iam-roles-for-amazon-ec2.html If IAM roles are not used you need to specify them either in a pillar or in the minion's config file: .. code-block:: yaml elb.keyid: GKTADJGHEIQSXMKKRBJ08H elb.key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs A region may also be specified in the configuration: .. code-block:: yaml elb.region: us-east-1 If a region is not specified, the default is us-east-1. It's also possible to specify key, keyid and region via a profile, either as a passed in dict, or as a string to pull from pillars or minion config: .. code-block:: yaml myprofile: keyid: GKTADJGHEIQSXMKKRBJ08H key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs region: us-east-1 :depends: boto >= 2.33.0 ''' # keep lint from choking on _get_conn and _cache_id # pylint: disable=E0602 from __future__ import absolute_import, print_function, unicode_literals # Import Python libs import logging import time log = logging.getLogger(__name__) # Import Salt libs import salt.utils.json import salt.utils.odict as odict import salt.utils.versions # Import third party libs from salt.ext import six try: import boto import boto.ec2 # pylint: enable=unused-import from boto.ec2.elb import HealthCheck from boto.ec2.elb.attributes import AccessLogAttribute from boto.ec2.elb.attributes import ConnectionDrainingAttribute from boto.ec2.elb.attributes import ConnectionSettingAttribute from boto.ec2.elb.attributes import CrossZoneLoadBalancingAttribute logging.getLogger('boto').setLevel(logging.CRITICAL) HAS_BOTO = True except ImportError: HAS_BOTO = False def __virtual__(): ''' Only load if boto libraries exist. ''' # connection settings were added in 2.33.0 has_boto_reqs = salt.utils.versions.check_boto_reqs( boto_ver='2.33.0', check_boto3=False ) if has_boto_reqs is True: __utils__['boto.assign_funcs'](__name__, 'elb', module='ec2.elb', pack=__salt__) return has_boto_reqs def exists(name, region=None, key=None, keyid=None, profile=None): ''' Check to see if an ELB exists. CLI example: .. code-block:: bash salt myminion boto_elb.exists myelb region=us-east-1 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: elb = conn.get_all_load_balancers(load_balancer_names=[name]) if elb: return True else: log.debug('The load balancer does not exist in region %s', region) return False except boto.exception.BotoServerError as error: log.warning(error) return False def get_all_elbs(region=None, key=None, keyid=None, profile=None): ''' Return all load balancers associated with an account CLI example: .. code-block:: bash salt myminion boto_elb.get_all_elbs region=us-east-1 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: return [e for e in conn.get_all_load_balancers()] except boto.exception.BotoServerError as error: log.warning(error) return [] def list_elbs(region=None, key=None, keyid=None, profile=None): ''' Return names of all load balancers associated with an account CLI example: .. code-block:: bash salt myminion boto_elb.list_elbs region=us-east-1 ''' return [e.name for e in get_all_elbs(region=region, key=key, keyid=keyid, profile=profile)] def get_elb_config(name, region=None, key=None, keyid=None, profile=None): ''' Get an ELB configuration. CLI example: .. code-block:: bash salt myminion boto_elb.exists myelb region=us-east-1 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) retries = 30 while retries: try: lb = conn.get_all_load_balancers(load_balancer_names=[name]) lb = lb[0] ret = {} ret['availability_zones'] = lb.availability_zones listeners = [] for _listener in lb.listeners: listener_dict = {} listener_dict['elb_port'] = _listener.load_balancer_port listener_dict['elb_protocol'] = _listener.protocol listener_dict['instance_port'] = _listener.instance_port listener_dict['instance_protocol'] = _listener.instance_protocol listener_dict['policies'] = _listener.policy_names if _listener.ssl_certificate_id: listener_dict['certificate'] = _listener.ssl_certificate_id listeners.append(listener_dict) ret['listeners'] = listeners backends = [] for _backend in lb.backends: bs_dict = {} bs_dict['instance_port'] = _backend.instance_port bs_dict['policies'] = [p.policy_name for p in _backend.policies] backends.append(bs_dict) ret['backends'] = backends ret['subnets'] = lb.subnets ret['security_groups'] = lb.security_groups ret['scheme'] = lb.scheme ret['dns_name'] = lb.dns_name ret['tags'] = _get_all_tags(conn, name) lb_policy_lists = [ lb.policies.app_cookie_stickiness_policies, lb.policies.lb_cookie_stickiness_policies, lb.policies.other_policies ] policies = [] for policy_list in lb_policy_lists: policies += [p.policy_name for p in policy_list] ret['policies'] = policies return ret except boto.exception.BotoServerError as error: if error.error_code == 'Throttling': log.debug('Throttled by AWS API, will retry in 5 seconds.') time.sleep(5) retries -= 1 continue log.error('Error fetching config for ELB %s: %s', name, error.message) log.error(error) return {} return {} def listener_dict_to_tuple(listener): ''' Convert an ELB listener dict into a listener tuple used by certain parts of the AWS ELB API. CLI example: .. code-block:: bash salt myminion boto_elb.listener_dict_to_tuple '{"elb_port":80,"instance_port":80,"elb_protocol":"HTTP"}' ''' # We define all listeners as complex listeners. if 'instance_protocol' not in listener: instance_protocol = listener['elb_protocol'].upper() else: instance_protocol = listener['instance_protocol'].upper() listener_tuple = [listener['elb_port'], listener['instance_port'], listener['elb_protocol'], instance_protocol] if 'certificate' in listener: listener_tuple.append(listener['certificate']) return tuple(listener_tuple) def create(name, availability_zones, listeners, subnets=None, security_groups=None, scheme='internet-facing', region=None, key=None, keyid=None, profile=None): ''' Create an ELB CLI example to create an ELB: .. code-block:: bash salt myminion boto_elb.create myelb '["us-east-1a", "us-east-1e"]' '{"elb_port": 443, "elb_protocol": "HTTPS", ...}' region=us-east-1 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if exists(name, region, key, keyid, profile): return True if isinstance(availability_zones, six.string_types): availability_zones = salt.utils.json.loads(availability_zones) if isinstance(listeners, six.string_types): listeners = salt.utils.json.loads(listeners) _complex_listeners = [] for listener in listeners: _complex_listeners.append(listener_dict_to_tuple(listener)) try: lb = conn.create_load_balancer(name=name, zones=availability_zones, subnets=subnets, security_groups=security_groups, scheme=scheme, complex_listeners=_complex_listeners) if lb: log.info('Created ELB %s', name) return True else: log.error('Failed to create ELB %s', name) return False except boto.exception.BotoServerError as error: log.error('Failed to create ELB %s: %s: %s', name, error.error_code, error.message, exc_info_on_loglevel=logging.DEBUG) return False def delete(name, region=None, key=None, keyid=None, profile=None): ''' Delete an ELB. CLI example to delete an ELB: .. code-block:: bash salt myminion boto_elb.delete myelb region=us-east-1 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not exists(name, region, key, keyid, profile): return True try: conn.delete_load_balancer(name) log.info('Deleted ELB %s.', name) return True except boto.exception.BotoServerError as error: log.error('Failed to delete ELB %s', name, exc_info_on_loglevel=logging.DEBUG) return False def create_listeners(name, listeners, region=None, key=None, keyid=None, profile=None): ''' Create listeners on an ELB. CLI example: .. code-block:: bash salt myminion boto_elb.create_listeners myelb '[["HTTPS", "HTTP", 443, 80, "arn:aws:iam::11 11111:server-certificate/mycert"]]' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if isinstance(listeners, six.string_types): listeners = salt.utils.json.loads(listeners) _complex_listeners = [] for listener in listeners: _complex_listeners.append(listener_dict_to_tuple(listener)) try: conn.create_load_balancer_listeners(name, [], _complex_listeners) log.info('Created ELB listeners on %s', name) return True except boto.exception.BotoServerError as error: log.error('Failed to create ELB listeners on %s: %s', name, error, exc_info_on_loglevel=logging.DEBUG) return False def delete_listeners(name, ports, region=None, key=None, keyid=None, profile=None): ''' Delete listeners on an ELB. CLI example: .. code-block:: bash salt myminion boto_elb.delete_listeners myelb '[80,443]' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if isinstance(ports, six.string_types): ports = salt.utils.json.loads(ports) try: conn.delete_load_balancer_listeners(name, ports) log.info('Deleted ELB listeners on %s', name) return True except boto.exception.BotoServerError as error: log.error('Failed to delete ELB listeners on %s: %s', name, error, exc_info_on_loglevel=logging.DEBUG) return False def enable_availability_zones(name, availability_zones, region=None, key=None, keyid=None, profile=None): ''' Enable availability zones for ELB. CLI example: .. code-block:: bash salt myminion boto_elb.enable_availability_zones myelb '["us-east-1a"]' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if isinstance(availability_zones, six.string_types): availability_zones = salt.utils.json.loads(availability_zones) try: conn.enable_availability_zones(name, availability_zones) log.info('Enabled availability_zones on ELB %s', name) return True except boto.exception.BotoServerError as error: log.error('Failed to enable availability_zones on ELB %s: %s', name, error) return False def disable_availability_zones(name, availability_zones, region=None, key=None, keyid=None, profile=None): ''' Disable availability zones for ELB. CLI example: .. code-block:: bash salt myminion boto_elb.disable_availability_zones myelb '["us-east-1a"]' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if isinstance(availability_zones, six.string_types): availability_zones = salt.utils.json.loads(availability_zones) try: conn.disable_availability_zones(name, availability_zones) log.info('Disabled availability_zones on ELB %s', name) return True except boto.exception.BotoServerError as error: log.error('Failed to disable availability_zones on ELB %s: %s', name, error, exc_info_on_loglevel=logging.DEBUG) return False def attach_subnets(name, subnets, region=None, key=None, keyid=None, profile=None): ''' Attach ELB to subnets. CLI example: .. code-block:: bash salt myminion boto_elb.attach_subnets myelb '["mysubnet"]' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if isinstance(subnets, six.string_types): subnets = salt.utils.json.loads(subnets) try: conn.attach_lb_to_subnets(name, subnets) log.info('Attached ELB %s on subnets.', name) return True except boto.exception.BotoServerError as error: log.error('Failed to attach ELB %s on subnets: %s', name, error, exc_info_on_loglevel=logging.DEBUG) return False def detach_subnets(name, subnets, region=None, key=None, keyid=None, profile=None): ''' Detach ELB from subnets. CLI example: .. code-block:: bash salt myminion boto_elb.detach_subnets myelb '["mysubnet"]' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if isinstance(subnets, six.string_types): subnets = salt.utils.json.loads(subnets) try: conn.detach_lb_from_subnets(name, subnets) log.info('Detached ELB %s from subnets.', name) return True except boto.exception.BotoServerError as error: log.error('Failed to detach ELB %s from subnets: %s', name, error, exc_info_on_loglevel=logging.DEBUG) return False def get_attributes(name, region=None, key=None, keyid=None, profile=None): ''' Check to see if attributes are set on an ELB. CLI example: .. code-block:: bash salt myminion boto_elb.get_attributes myelb ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) retries = 30 while retries: try: lbattrs = conn.get_all_lb_attributes(name) ret = odict.OrderedDict() ret['access_log'] = odict.OrderedDict() ret['cross_zone_load_balancing'] = odict.OrderedDict() ret['connection_draining'] = odict.OrderedDict() ret['connecting_settings'] = odict.OrderedDict() al = lbattrs.access_log czlb = lbattrs.cross_zone_load_balancing cd = lbattrs.connection_draining cs = lbattrs.connecting_settings ret['access_log']['enabled'] = al.enabled ret['access_log']['s3_bucket_name'] = al.s3_bucket_name ret['access_log']['s3_bucket_prefix'] = al.s3_bucket_prefix ret['access_log']['emit_interval'] = al.emit_interval ret['cross_zone_load_balancing']['enabled'] = czlb.enabled ret['connection_draining']['enabled'] = cd.enabled ret['connection_draining']['timeout'] = cd.timeout ret['connecting_settings']['idle_timeout'] = cs.idle_timeout return ret except boto.exception.BotoServerError as e: if e.error_code == 'Throttling': log.debug("Throttled by AWS API, will retry in 5 seconds...") time.sleep(5) retries -= 1 continue log.error('ELB %s does not exist: %s', name, e.message) return {} return {} def set_attributes(name, attributes, region=None, key=None, keyid=None, profile=None): ''' Set attributes on an ELB. name (string) Name of the ELB instance to set attributes for attributes A dict of attributes to set. Valid attributes are: access_log (dict) enabled (bool) Enable storage of access logs. s3_bucket_name (string) The name of the S3 bucket to place logs. s3_bucket_prefix (string) Prefix for the log file name. emit_interval (int) Interval for storing logs in S3 in minutes. Valid values are 5 and 60. connection_draining (dict) enabled (bool) Enable connection draining. timeout (int) Maximum allowed time in seconds for sending existing connections to an instance that is deregistering or unhealthy. Default is 300. cross_zone_load_balancing (dict) enabled (bool) Enable cross-zone load balancing. CLI example to set attributes on an ELB: .. code-block:: bash salt myminion boto_elb.set_attributes myelb '{"access_log": {"enabled": "true", "s3_bucket_name": "mybucket", "s3_bucket_prefix": "mylogs/", "emit_interval": "5"}}' region=us-east-1 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) al = attributes.get('access_log', {}) czlb = attributes.get('cross_zone_load_balancing', {}) cd = attributes.get('connection_draining', {}) cs = attributes.get('connecting_settings', {}) if not al and not czlb and not cd and not cs: log.error('No supported attributes for ELB.') return False if al: _al = AccessLogAttribute() _al.enabled = al.get('enabled', False) if not _al.enabled: msg = 'Access log attribute configured, but enabled config missing' log.error(msg) return False _al.s3_bucket_name = al.get('s3_bucket_name', None) _al.s3_bucket_prefix = al.get('s3_bucket_prefix', None) _al.emit_interval = al.get('emit_interval', None) added_attr = conn.modify_lb_attribute(name, 'accessLog', _al) if added_attr: log.info('Added access_log attribute to %s elb.', name) else: log.error('Failed to add access_log attribute to %s elb.', name) return False if czlb: _czlb = CrossZoneLoadBalancingAttribute() _czlb.enabled = czlb['enabled'] added_attr = conn.modify_lb_attribute(name, 'crossZoneLoadBalancing', _czlb.enabled) if added_attr: log.info('Added cross_zone_load_balancing attribute to %s elb.', name) else: log.error('Failed to add cross_zone_load_balancing attribute.') return False if cd: _cd = ConnectionDrainingAttribute() _cd.enabled = cd['enabled'] _cd.timeout = cd.get('timeout', 300) added_attr = conn.modify_lb_attribute(name, 'connectionDraining', _cd) if added_attr: log.info('Added connection_draining attribute to %s elb.', name) else: log.error('Failed to add connection_draining attribute.') return False if cs: _cs = ConnectionSettingAttribute() _cs.idle_timeout = cs.get('idle_timeout', 60) added_attr = conn.modify_lb_attribute(name, 'connectingSettings', _cs) if added_attr: log.info('Added connecting_settings attribute to %s elb.', name) else: log.error('Failed to add connecting_settings attribute.') return False return True def get_health_check(name, region=None, key=None, keyid=None, profile=None): ''' Get the health check configured for this ELB. CLI example: .. code-block:: bash salt myminion boto_elb.get_health_check myelb ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) retries = 30 while True: try: lb = conn.get_all_load_balancers(load_balancer_names=[name]) lb = lb[0] ret = odict.OrderedDict() hc = lb.health_check ret['interval'] = hc.interval ret['target'] = hc.target ret['healthy_threshold'] = hc.healthy_threshold ret['timeout'] = hc.timeout ret['unhealthy_threshold'] = hc.unhealthy_threshold return ret except boto.exception.BotoServerError as e: if retries and e.code == 'Throttling': log.debug('Throttled by AWS API, will retry in 5 seconds.') time.sleep(5) retries -= 1 continue log.error('ELB %s not found.', name, exc_info_on_logleve=logging.DEBUG) return {} def set_health_check(name, health_check, region=None, key=None, keyid=None, profile=None): ''' Set attributes on an ELB. CLI example to set attributes on an ELB: .. code-block:: bash salt myminion boto_elb.set_health_check myelb '{"target": "HTTP:80/"}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) retries = 30 hc = HealthCheck(**health_check) while True: try: conn.configure_health_check(name, hc) log.info('Configured health check on ELB %s', name) return True except boto.exception.BotoServerError as error: if retries and e.code == 'Throttling': log.debug('Throttled by AWS API, will retry in 5 seconds.') time.sleep(5) retries -= 1 continue log.exception('Failed to configure health check on ELB %s', name) return False def register_instances(name, instances, region=None, key=None, keyid=None, profile=None): ''' Register instances with an ELB. Instances is either a string instance id or a list of string instance id's. Returns: - ``True``: instance(s) registered successfully - ``False``: instance(s) failed to be registered CLI example: .. code-block:: bash salt myminion boto_elb.register_instances myelb instance_id salt myminion boto_elb.register_instances myelb "[instance_id,instance_id]" ''' # convert instances to list type, enabling consistent use of instances # variable throughout the register_instances method if isinstance(instances, six.string_types) or isinstance(instances, six.text_type): instances = [instances] conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: registered_instances = conn.register_instances(name, instances) except boto.exception.BotoServerError as error: log.warning(error) return False registered_instance_ids = [instance.id for instance in registered_instances] # register_failues is a set that will contain any instances that were not # able to be registered with the given ELB register_failures = set(instances).difference(set(registered_instance_ids)) if register_failures: log.warning('Instance(s): %s not registered with ELB %s.', list(register_failures), name) register_result = False else: register_result = True return register_result def deregister_instances(name, instances, region=None, key=None, keyid=None, profile=None): ''' Deregister instances with an ELB. Instances is either a string instance id or a list of string instance id's. Returns: - ``True``: instance(s) deregistered successfully - ``False``: instance(s) failed to be deregistered - ``None``: instance(s) not valid or not registered, no action taken CLI example: .. code-block:: bash salt myminion boto_elb.deregister_instances myelb instance_id salt myminion boto_elb.deregister_instances myelb "[instance_id, instance_id]" ''' # convert instances to list type, enabling consistent use of instances # variable throughout the deregister_instances method if isinstance(instances, six.string_types) or isinstance(instances, six.text_type): instances = [instances] conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: registered_instances = conn.deregister_instances(name, instances) except boto.exception.BotoServerError as error: # if the instance(s) given as an argument are not members of the ELB # boto returns error.error_code == 'InvalidInstance' # deregister_instances returns "None" because the instances are # effectively deregistered from ELB if error.error_code == 'InvalidInstance': log.warning( 'One or more of instance(s) %s are not part of ELB %s. ' 'deregister_instances not performed.', instances, name ) return None else: log.warning(error) return False registered_instance_ids = [instance.id for instance in registered_instances] # deregister_failures is a set that will contain any instances that were # unable to be deregistered from the given ELB deregister_failures = set(instances).intersection(set(registered_instance_ids)) if deregister_failures: log.warning( 'Instance(s): %s not deregistered from ELB %s.', list(deregister_failures), name ) deregister_result = False else: deregister_result = True return deregister_result def set_instances(name, instances, test=False, region=None, key=None, keyid=None, profile=None): ''' Set the instances assigned to an ELB to exactly the list given CLI example: .. code-block:: bash salt myminion boto_elb.set_instances myelb region=us-east-1 instances="[instance_id,instance_id]" ''' ret = True current = set([i['instance_id'] for i in get_instance_health(name, region, key, keyid, profile)]) desired = set(instances) add = desired - current remove = current - desired if test: return bool(add or remove) if remove: if deregister_instances(name, list(remove), region, key, keyid, profile) is False: ret = False if add: if register_instances(name, list(add), region, key, keyid, profile) is False: ret = False return ret def get_instance_health(name, region=None, key=None, keyid=None, profile=None, instances=None): ''' Get a list of instances and their health state CLI example: .. code-block:: bash salt myminion boto_elb.get_instance_health myelb salt myminion boto_elb.get_instance_health myelb region=us-east-1 instances="[instance_id,instance_id]" ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: instance_states = conn.describe_instance_health(name, instances) ret = [] for _instance in instance_states: ret.append({'instance_id': _instance.instance_id, 'description': _instance.description, 'state': _instance.state, 'reason_code': _instance.reason_code }) return ret except boto.exception.BotoServerError as error: log.debug(error) return [] def create_policy(name, policy_name, policy_type, policy, region=None, key=None, keyid=None, profile=None): ''' Create an ELB policy. .. versionadded:: 2016.3.0 CLI example: .. code-block:: bash salt myminion boto_elb.create_policy myelb mypolicy LBCookieStickinessPolicyType '{"CookieExpirationPeriod": 3600}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not exists(name, region, key, keyid, profile): return False try: success = conn.create_lb_policy(name, policy_name, policy_type, policy) if success: log.info('Created policy %s on ELB %s', policy_name, name) return True else: log.error('Failed to create policy %s on ELB %s', policy_name, name) return False except boto.exception.BotoServerError as e: log.error('Failed to create policy %s on ELB %s: %s', policy_name, name, e.message, exc_info_on_loglevel=logging.DEBUG) return False def delete_policy(name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Delete an ELB policy. .. versionadded:: 2016.3.0 CLI example: .. code-block:: bash salt myminion boto_elb.delete_policy myelb mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not exists(name, region, key, keyid, profile): return True try: conn.delete_lb_policy(name, policy_name) log.info('Deleted policy %s on ELB %s', policy_name, name) return True except boto.exception.BotoServerError as e: log.error('Failed to delete policy %s on ELB %s: %s', policy_name, name, e.message, exc_info_on_loglevel=logging.DEBUG) return False def set_listener_policy(name, port, policies=None, region=None, key=None, keyid=None, profile=None): ''' Set the policies of an ELB listener. .. versionadded:: 2016.3.0 CLI example: .. code-block:: Bash salt myminion boto_elb.set_listener_policy myelb 443 "[policy1,policy2]" ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not exists(name, region, key, keyid, profile): return True if policies is None: policies = [] try: conn.set_lb_policies_of_listener(name, port, policies) log.info('Set policies %s on ELB %s listener %s', policies, name, port) except boto.exception.BotoServerError as e: log.info('Failed to set policy %s on ELB %s listener %s: %s', policies, name, port, e.message, exc_info_on_loglevel=logging.DEBUG) return False return True def set_backend_policy(name, port, policies=None, region=None, key=None, keyid=None, profile=None): ''' Set the policies of an ELB backend server. CLI example: salt myminion boto_elb.set_backend_policy myelb 443 "[policy1,policy2]" ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not exists(name, region, key, keyid, profile): return True if policies is None: policies = [] try: conn.set_lb_policies_of_backend_server(name, port, policies) log.info('Set policies %s on ELB %s backend server %s', policies, name, port) except boto.exception.BotoServerError as e: log.info('Failed to set policy %s on ELB %s backend server %s: %s', policies, name, port, e.message, exc_info_on_loglevel=logging.DEBUG) return False return True def set_tags(name, tags, region=None, key=None, keyid=None, profile=None): ''' Add the tags on an ELB .. versionadded:: 2016.3.0 name name of the ELB tags dict of name/value pair tags CLI Example: .. code-block:: bash salt myminion boto_elb.set_tags my-elb-name "{'Tag1': 'Value', 'Tag2': 'Another Value'}" ''' if exists(name, region, key, keyid, profile): conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) ret = _add_tags(conn, name, tags) return ret else: return False def delete_tags(name, tags, region=None, key=None, keyid=None, profile=None): ''' Add the tags on an ELB name name of the ELB tags list of tags to remove CLI Example: .. code-block:: bash salt myminion boto_elb.delete_tags my-elb-name ['TagToRemove1', 'TagToRemove2'] ''' if exists(name, region, key, keyid, profile): conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) ret = _remove_tags(conn, name, tags) return ret else: return False def _build_tag_param_list(params, tags): ''' helper function to build a tag parameter list to send ''' keys = sorted(tags.keys()) i = 1 for key in keys: value = tags[key] params['Tags.member.{0}.Key'.format(i)] = key if value is not None: params['Tags.member.{0}.Value'.format(i)] = value i += 1 def _get_all_tags(conn, load_balancer_names=None): ''' Retrieve all the metadata tags associated with your ELB(s). :type load_balancer_names: list :param load_balancer_names: An optional list of load balancer names. :rtype: list :return: A list of :class:`boto.ec2.elb.tag.Tag` objects ''' params = {} if load_balancer_names: conn.build_list_params(params, load_balancer_names, 'LoadBalancerNames.member.%d') tags = conn.get_object( 'DescribeTags', params, __utils__['boto_elb_tag.get_tag_descriptions'](), verb='POST' ) if tags[load_balancer_names]: return tags[load_balancer_names] else: return None def _add_tags(conn, load_balancer_names, tags): ''' Create new metadata tags for the specified resource ids. :type load_balancer_names: list :param load_balancer_names: A list of load balancer names. :type tags: dict :param tags: A dictionary containing the name/value pairs. If you want to create only a tag name, the value for that tag should be the empty string (e.g. ''). ''' params = {} conn.build_list_params(params, load_balancer_names, 'LoadBalancerNames.member.%d') _build_tag_param_list(params, tags) return conn.get_status('AddTags', params, verb='POST') def _remove_tags(conn, load_balancer_names, tags): ''' Delete metadata tags for the specified resource ids. :type load_balancer_names: list :param load_balancer_names: A list of load balancer names. :type tags: list :param tags: A list containing just tag names for the tags to be deleted. ''' params = {} conn.build_list_params(params, load_balancer_names, 'LoadBalancerNames.member.%d') conn.build_list_params(params, tags, 'Tags.member.%d.Key') return conn.get_status('RemoveTags', params, verb='POST')
saltstack/salt
salt/modules/boto_elb.py
get_attributes
python
def get_attributes(name, region=None, key=None, keyid=None, profile=None): ''' Check to see if attributes are set on an ELB. CLI example: .. code-block:: bash salt myminion boto_elb.get_attributes myelb ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) retries = 30 while retries: try: lbattrs = conn.get_all_lb_attributes(name) ret = odict.OrderedDict() ret['access_log'] = odict.OrderedDict() ret['cross_zone_load_balancing'] = odict.OrderedDict() ret['connection_draining'] = odict.OrderedDict() ret['connecting_settings'] = odict.OrderedDict() al = lbattrs.access_log czlb = lbattrs.cross_zone_load_balancing cd = lbattrs.connection_draining cs = lbattrs.connecting_settings ret['access_log']['enabled'] = al.enabled ret['access_log']['s3_bucket_name'] = al.s3_bucket_name ret['access_log']['s3_bucket_prefix'] = al.s3_bucket_prefix ret['access_log']['emit_interval'] = al.emit_interval ret['cross_zone_load_balancing']['enabled'] = czlb.enabled ret['connection_draining']['enabled'] = cd.enabled ret['connection_draining']['timeout'] = cd.timeout ret['connecting_settings']['idle_timeout'] = cs.idle_timeout return ret except boto.exception.BotoServerError as e: if e.error_code == 'Throttling': log.debug("Throttled by AWS API, will retry in 5 seconds...") time.sleep(5) retries -= 1 continue log.error('ELB %s does not exist: %s', name, e.message) return {} return {}
Check to see if attributes are set on an ELB. CLI example: .. code-block:: bash salt myminion boto_elb.get_attributes myelb
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_elb.py#L482-L524
null
# -*- coding: utf-8 -*- ''' Connection module for Amazon ELB .. versionadded:: 2014.7.0 :configuration: This module accepts explicit elb credentials but can also utilize IAM roles assigned to the instance through Instance Profiles. Dynamic credentials are then automatically obtained from AWS API and no further configuration is necessary. More Information available at: .. code-block:: text http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/iam-roles-for-amazon-ec2.html If IAM roles are not used you need to specify them either in a pillar or in the minion's config file: .. code-block:: yaml elb.keyid: GKTADJGHEIQSXMKKRBJ08H elb.key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs A region may also be specified in the configuration: .. code-block:: yaml elb.region: us-east-1 If a region is not specified, the default is us-east-1. It's also possible to specify key, keyid and region via a profile, either as a passed in dict, or as a string to pull from pillars or minion config: .. code-block:: yaml myprofile: keyid: GKTADJGHEIQSXMKKRBJ08H key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs region: us-east-1 :depends: boto >= 2.33.0 ''' # keep lint from choking on _get_conn and _cache_id # pylint: disable=E0602 from __future__ import absolute_import, print_function, unicode_literals # Import Python libs import logging import time log = logging.getLogger(__name__) # Import Salt libs import salt.utils.json import salt.utils.odict as odict import salt.utils.versions # Import third party libs from salt.ext import six try: import boto import boto.ec2 # pylint: enable=unused-import from boto.ec2.elb import HealthCheck from boto.ec2.elb.attributes import AccessLogAttribute from boto.ec2.elb.attributes import ConnectionDrainingAttribute from boto.ec2.elb.attributes import ConnectionSettingAttribute from boto.ec2.elb.attributes import CrossZoneLoadBalancingAttribute logging.getLogger('boto').setLevel(logging.CRITICAL) HAS_BOTO = True except ImportError: HAS_BOTO = False def __virtual__(): ''' Only load if boto libraries exist. ''' # connection settings were added in 2.33.0 has_boto_reqs = salt.utils.versions.check_boto_reqs( boto_ver='2.33.0', check_boto3=False ) if has_boto_reqs is True: __utils__['boto.assign_funcs'](__name__, 'elb', module='ec2.elb', pack=__salt__) return has_boto_reqs def exists(name, region=None, key=None, keyid=None, profile=None): ''' Check to see if an ELB exists. CLI example: .. code-block:: bash salt myminion boto_elb.exists myelb region=us-east-1 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: elb = conn.get_all_load_balancers(load_balancer_names=[name]) if elb: return True else: log.debug('The load balancer does not exist in region %s', region) return False except boto.exception.BotoServerError as error: log.warning(error) return False def get_all_elbs(region=None, key=None, keyid=None, profile=None): ''' Return all load balancers associated with an account CLI example: .. code-block:: bash salt myminion boto_elb.get_all_elbs region=us-east-1 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: return [e for e in conn.get_all_load_balancers()] except boto.exception.BotoServerError as error: log.warning(error) return [] def list_elbs(region=None, key=None, keyid=None, profile=None): ''' Return names of all load balancers associated with an account CLI example: .. code-block:: bash salt myminion boto_elb.list_elbs region=us-east-1 ''' return [e.name for e in get_all_elbs(region=region, key=key, keyid=keyid, profile=profile)] def get_elb_config(name, region=None, key=None, keyid=None, profile=None): ''' Get an ELB configuration. CLI example: .. code-block:: bash salt myminion boto_elb.exists myelb region=us-east-1 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) retries = 30 while retries: try: lb = conn.get_all_load_balancers(load_balancer_names=[name]) lb = lb[0] ret = {} ret['availability_zones'] = lb.availability_zones listeners = [] for _listener in lb.listeners: listener_dict = {} listener_dict['elb_port'] = _listener.load_balancer_port listener_dict['elb_protocol'] = _listener.protocol listener_dict['instance_port'] = _listener.instance_port listener_dict['instance_protocol'] = _listener.instance_protocol listener_dict['policies'] = _listener.policy_names if _listener.ssl_certificate_id: listener_dict['certificate'] = _listener.ssl_certificate_id listeners.append(listener_dict) ret['listeners'] = listeners backends = [] for _backend in lb.backends: bs_dict = {} bs_dict['instance_port'] = _backend.instance_port bs_dict['policies'] = [p.policy_name for p in _backend.policies] backends.append(bs_dict) ret['backends'] = backends ret['subnets'] = lb.subnets ret['security_groups'] = lb.security_groups ret['scheme'] = lb.scheme ret['dns_name'] = lb.dns_name ret['tags'] = _get_all_tags(conn, name) lb_policy_lists = [ lb.policies.app_cookie_stickiness_policies, lb.policies.lb_cookie_stickiness_policies, lb.policies.other_policies ] policies = [] for policy_list in lb_policy_lists: policies += [p.policy_name for p in policy_list] ret['policies'] = policies return ret except boto.exception.BotoServerError as error: if error.error_code == 'Throttling': log.debug('Throttled by AWS API, will retry in 5 seconds.') time.sleep(5) retries -= 1 continue log.error('Error fetching config for ELB %s: %s', name, error.message) log.error(error) return {} return {} def listener_dict_to_tuple(listener): ''' Convert an ELB listener dict into a listener tuple used by certain parts of the AWS ELB API. CLI example: .. code-block:: bash salt myminion boto_elb.listener_dict_to_tuple '{"elb_port":80,"instance_port":80,"elb_protocol":"HTTP"}' ''' # We define all listeners as complex listeners. if 'instance_protocol' not in listener: instance_protocol = listener['elb_protocol'].upper() else: instance_protocol = listener['instance_protocol'].upper() listener_tuple = [listener['elb_port'], listener['instance_port'], listener['elb_protocol'], instance_protocol] if 'certificate' in listener: listener_tuple.append(listener['certificate']) return tuple(listener_tuple) def create(name, availability_zones, listeners, subnets=None, security_groups=None, scheme='internet-facing', region=None, key=None, keyid=None, profile=None): ''' Create an ELB CLI example to create an ELB: .. code-block:: bash salt myminion boto_elb.create myelb '["us-east-1a", "us-east-1e"]' '{"elb_port": 443, "elb_protocol": "HTTPS", ...}' region=us-east-1 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if exists(name, region, key, keyid, profile): return True if isinstance(availability_zones, six.string_types): availability_zones = salt.utils.json.loads(availability_zones) if isinstance(listeners, six.string_types): listeners = salt.utils.json.loads(listeners) _complex_listeners = [] for listener in listeners: _complex_listeners.append(listener_dict_to_tuple(listener)) try: lb = conn.create_load_balancer(name=name, zones=availability_zones, subnets=subnets, security_groups=security_groups, scheme=scheme, complex_listeners=_complex_listeners) if lb: log.info('Created ELB %s', name) return True else: log.error('Failed to create ELB %s', name) return False except boto.exception.BotoServerError as error: log.error('Failed to create ELB %s: %s: %s', name, error.error_code, error.message, exc_info_on_loglevel=logging.DEBUG) return False def delete(name, region=None, key=None, keyid=None, profile=None): ''' Delete an ELB. CLI example to delete an ELB: .. code-block:: bash salt myminion boto_elb.delete myelb region=us-east-1 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not exists(name, region, key, keyid, profile): return True try: conn.delete_load_balancer(name) log.info('Deleted ELB %s.', name) return True except boto.exception.BotoServerError as error: log.error('Failed to delete ELB %s', name, exc_info_on_loglevel=logging.DEBUG) return False def create_listeners(name, listeners, region=None, key=None, keyid=None, profile=None): ''' Create listeners on an ELB. CLI example: .. code-block:: bash salt myminion boto_elb.create_listeners myelb '[["HTTPS", "HTTP", 443, 80, "arn:aws:iam::11 11111:server-certificate/mycert"]]' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if isinstance(listeners, six.string_types): listeners = salt.utils.json.loads(listeners) _complex_listeners = [] for listener in listeners: _complex_listeners.append(listener_dict_to_tuple(listener)) try: conn.create_load_balancer_listeners(name, [], _complex_listeners) log.info('Created ELB listeners on %s', name) return True except boto.exception.BotoServerError as error: log.error('Failed to create ELB listeners on %s: %s', name, error, exc_info_on_loglevel=logging.DEBUG) return False def delete_listeners(name, ports, region=None, key=None, keyid=None, profile=None): ''' Delete listeners on an ELB. CLI example: .. code-block:: bash salt myminion boto_elb.delete_listeners myelb '[80,443]' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if isinstance(ports, six.string_types): ports = salt.utils.json.loads(ports) try: conn.delete_load_balancer_listeners(name, ports) log.info('Deleted ELB listeners on %s', name) return True except boto.exception.BotoServerError as error: log.error('Failed to delete ELB listeners on %s: %s', name, error, exc_info_on_loglevel=logging.DEBUG) return False def apply_security_groups(name, security_groups, region=None, key=None, keyid=None, profile=None): ''' Apply security groups to ELB. CLI example: .. code-block:: bash salt myminion boto_elb.apply_security_groups myelb '["mysecgroup1"]' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if isinstance(security_groups, six.string_types): security_groups = salt.utils.json.loads(security_groups) try: conn.apply_security_groups_to_lb(name, security_groups) log.info('Applied security_groups on ELB %s', name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to appply security_groups on ELB %s: %s', name, e.message) return False def enable_availability_zones(name, availability_zones, region=None, key=None, keyid=None, profile=None): ''' Enable availability zones for ELB. CLI example: .. code-block:: bash salt myminion boto_elb.enable_availability_zones myelb '["us-east-1a"]' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if isinstance(availability_zones, six.string_types): availability_zones = salt.utils.json.loads(availability_zones) try: conn.enable_availability_zones(name, availability_zones) log.info('Enabled availability_zones on ELB %s', name) return True except boto.exception.BotoServerError as error: log.error('Failed to enable availability_zones on ELB %s: %s', name, error) return False def disable_availability_zones(name, availability_zones, region=None, key=None, keyid=None, profile=None): ''' Disable availability zones for ELB. CLI example: .. code-block:: bash salt myminion boto_elb.disable_availability_zones myelb '["us-east-1a"]' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if isinstance(availability_zones, six.string_types): availability_zones = salt.utils.json.loads(availability_zones) try: conn.disable_availability_zones(name, availability_zones) log.info('Disabled availability_zones on ELB %s', name) return True except boto.exception.BotoServerError as error: log.error('Failed to disable availability_zones on ELB %s: %s', name, error, exc_info_on_loglevel=logging.DEBUG) return False def attach_subnets(name, subnets, region=None, key=None, keyid=None, profile=None): ''' Attach ELB to subnets. CLI example: .. code-block:: bash salt myminion boto_elb.attach_subnets myelb '["mysubnet"]' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if isinstance(subnets, six.string_types): subnets = salt.utils.json.loads(subnets) try: conn.attach_lb_to_subnets(name, subnets) log.info('Attached ELB %s on subnets.', name) return True except boto.exception.BotoServerError as error: log.error('Failed to attach ELB %s on subnets: %s', name, error, exc_info_on_loglevel=logging.DEBUG) return False def detach_subnets(name, subnets, region=None, key=None, keyid=None, profile=None): ''' Detach ELB from subnets. CLI example: .. code-block:: bash salt myminion boto_elb.detach_subnets myelb '["mysubnet"]' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if isinstance(subnets, six.string_types): subnets = salt.utils.json.loads(subnets) try: conn.detach_lb_from_subnets(name, subnets) log.info('Detached ELB %s from subnets.', name) return True except boto.exception.BotoServerError as error: log.error('Failed to detach ELB %s from subnets: %s', name, error, exc_info_on_loglevel=logging.DEBUG) return False def set_attributes(name, attributes, region=None, key=None, keyid=None, profile=None): ''' Set attributes on an ELB. name (string) Name of the ELB instance to set attributes for attributes A dict of attributes to set. Valid attributes are: access_log (dict) enabled (bool) Enable storage of access logs. s3_bucket_name (string) The name of the S3 bucket to place logs. s3_bucket_prefix (string) Prefix for the log file name. emit_interval (int) Interval for storing logs in S3 in minutes. Valid values are 5 and 60. connection_draining (dict) enabled (bool) Enable connection draining. timeout (int) Maximum allowed time in seconds for sending existing connections to an instance that is deregistering or unhealthy. Default is 300. cross_zone_load_balancing (dict) enabled (bool) Enable cross-zone load balancing. CLI example to set attributes on an ELB: .. code-block:: bash salt myminion boto_elb.set_attributes myelb '{"access_log": {"enabled": "true", "s3_bucket_name": "mybucket", "s3_bucket_prefix": "mylogs/", "emit_interval": "5"}}' region=us-east-1 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) al = attributes.get('access_log', {}) czlb = attributes.get('cross_zone_load_balancing', {}) cd = attributes.get('connection_draining', {}) cs = attributes.get('connecting_settings', {}) if not al and not czlb and not cd and not cs: log.error('No supported attributes for ELB.') return False if al: _al = AccessLogAttribute() _al.enabled = al.get('enabled', False) if not _al.enabled: msg = 'Access log attribute configured, but enabled config missing' log.error(msg) return False _al.s3_bucket_name = al.get('s3_bucket_name', None) _al.s3_bucket_prefix = al.get('s3_bucket_prefix', None) _al.emit_interval = al.get('emit_interval', None) added_attr = conn.modify_lb_attribute(name, 'accessLog', _al) if added_attr: log.info('Added access_log attribute to %s elb.', name) else: log.error('Failed to add access_log attribute to %s elb.', name) return False if czlb: _czlb = CrossZoneLoadBalancingAttribute() _czlb.enabled = czlb['enabled'] added_attr = conn.modify_lb_attribute(name, 'crossZoneLoadBalancing', _czlb.enabled) if added_attr: log.info('Added cross_zone_load_balancing attribute to %s elb.', name) else: log.error('Failed to add cross_zone_load_balancing attribute.') return False if cd: _cd = ConnectionDrainingAttribute() _cd.enabled = cd['enabled'] _cd.timeout = cd.get('timeout', 300) added_attr = conn.modify_lb_attribute(name, 'connectionDraining', _cd) if added_attr: log.info('Added connection_draining attribute to %s elb.', name) else: log.error('Failed to add connection_draining attribute.') return False if cs: _cs = ConnectionSettingAttribute() _cs.idle_timeout = cs.get('idle_timeout', 60) added_attr = conn.modify_lb_attribute(name, 'connectingSettings', _cs) if added_attr: log.info('Added connecting_settings attribute to %s elb.', name) else: log.error('Failed to add connecting_settings attribute.') return False return True def get_health_check(name, region=None, key=None, keyid=None, profile=None): ''' Get the health check configured for this ELB. CLI example: .. code-block:: bash salt myminion boto_elb.get_health_check myelb ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) retries = 30 while True: try: lb = conn.get_all_load_balancers(load_balancer_names=[name]) lb = lb[0] ret = odict.OrderedDict() hc = lb.health_check ret['interval'] = hc.interval ret['target'] = hc.target ret['healthy_threshold'] = hc.healthy_threshold ret['timeout'] = hc.timeout ret['unhealthy_threshold'] = hc.unhealthy_threshold return ret except boto.exception.BotoServerError as e: if retries and e.code == 'Throttling': log.debug('Throttled by AWS API, will retry in 5 seconds.') time.sleep(5) retries -= 1 continue log.error('ELB %s not found.', name, exc_info_on_logleve=logging.DEBUG) return {} def set_health_check(name, health_check, region=None, key=None, keyid=None, profile=None): ''' Set attributes on an ELB. CLI example to set attributes on an ELB: .. code-block:: bash salt myminion boto_elb.set_health_check myelb '{"target": "HTTP:80/"}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) retries = 30 hc = HealthCheck(**health_check) while True: try: conn.configure_health_check(name, hc) log.info('Configured health check on ELB %s', name) return True except boto.exception.BotoServerError as error: if retries and e.code == 'Throttling': log.debug('Throttled by AWS API, will retry in 5 seconds.') time.sleep(5) retries -= 1 continue log.exception('Failed to configure health check on ELB %s', name) return False def register_instances(name, instances, region=None, key=None, keyid=None, profile=None): ''' Register instances with an ELB. Instances is either a string instance id or a list of string instance id's. Returns: - ``True``: instance(s) registered successfully - ``False``: instance(s) failed to be registered CLI example: .. code-block:: bash salt myminion boto_elb.register_instances myelb instance_id salt myminion boto_elb.register_instances myelb "[instance_id,instance_id]" ''' # convert instances to list type, enabling consistent use of instances # variable throughout the register_instances method if isinstance(instances, six.string_types) or isinstance(instances, six.text_type): instances = [instances] conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: registered_instances = conn.register_instances(name, instances) except boto.exception.BotoServerError as error: log.warning(error) return False registered_instance_ids = [instance.id for instance in registered_instances] # register_failues is a set that will contain any instances that were not # able to be registered with the given ELB register_failures = set(instances).difference(set(registered_instance_ids)) if register_failures: log.warning('Instance(s): %s not registered with ELB %s.', list(register_failures), name) register_result = False else: register_result = True return register_result def deregister_instances(name, instances, region=None, key=None, keyid=None, profile=None): ''' Deregister instances with an ELB. Instances is either a string instance id or a list of string instance id's. Returns: - ``True``: instance(s) deregistered successfully - ``False``: instance(s) failed to be deregistered - ``None``: instance(s) not valid or not registered, no action taken CLI example: .. code-block:: bash salt myminion boto_elb.deregister_instances myelb instance_id salt myminion boto_elb.deregister_instances myelb "[instance_id, instance_id]" ''' # convert instances to list type, enabling consistent use of instances # variable throughout the deregister_instances method if isinstance(instances, six.string_types) or isinstance(instances, six.text_type): instances = [instances] conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: registered_instances = conn.deregister_instances(name, instances) except boto.exception.BotoServerError as error: # if the instance(s) given as an argument are not members of the ELB # boto returns error.error_code == 'InvalidInstance' # deregister_instances returns "None" because the instances are # effectively deregistered from ELB if error.error_code == 'InvalidInstance': log.warning( 'One or more of instance(s) %s are not part of ELB %s. ' 'deregister_instances not performed.', instances, name ) return None else: log.warning(error) return False registered_instance_ids = [instance.id for instance in registered_instances] # deregister_failures is a set that will contain any instances that were # unable to be deregistered from the given ELB deregister_failures = set(instances).intersection(set(registered_instance_ids)) if deregister_failures: log.warning( 'Instance(s): %s not deregistered from ELB %s.', list(deregister_failures), name ) deregister_result = False else: deregister_result = True return deregister_result def set_instances(name, instances, test=False, region=None, key=None, keyid=None, profile=None): ''' Set the instances assigned to an ELB to exactly the list given CLI example: .. code-block:: bash salt myminion boto_elb.set_instances myelb region=us-east-1 instances="[instance_id,instance_id]" ''' ret = True current = set([i['instance_id'] for i in get_instance_health(name, region, key, keyid, profile)]) desired = set(instances) add = desired - current remove = current - desired if test: return bool(add or remove) if remove: if deregister_instances(name, list(remove), region, key, keyid, profile) is False: ret = False if add: if register_instances(name, list(add), region, key, keyid, profile) is False: ret = False return ret def get_instance_health(name, region=None, key=None, keyid=None, profile=None, instances=None): ''' Get a list of instances and their health state CLI example: .. code-block:: bash salt myminion boto_elb.get_instance_health myelb salt myminion boto_elb.get_instance_health myelb region=us-east-1 instances="[instance_id,instance_id]" ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: instance_states = conn.describe_instance_health(name, instances) ret = [] for _instance in instance_states: ret.append({'instance_id': _instance.instance_id, 'description': _instance.description, 'state': _instance.state, 'reason_code': _instance.reason_code }) return ret except boto.exception.BotoServerError as error: log.debug(error) return [] def create_policy(name, policy_name, policy_type, policy, region=None, key=None, keyid=None, profile=None): ''' Create an ELB policy. .. versionadded:: 2016.3.0 CLI example: .. code-block:: bash salt myminion boto_elb.create_policy myelb mypolicy LBCookieStickinessPolicyType '{"CookieExpirationPeriod": 3600}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not exists(name, region, key, keyid, profile): return False try: success = conn.create_lb_policy(name, policy_name, policy_type, policy) if success: log.info('Created policy %s on ELB %s', policy_name, name) return True else: log.error('Failed to create policy %s on ELB %s', policy_name, name) return False except boto.exception.BotoServerError as e: log.error('Failed to create policy %s on ELB %s: %s', policy_name, name, e.message, exc_info_on_loglevel=logging.DEBUG) return False def delete_policy(name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Delete an ELB policy. .. versionadded:: 2016.3.0 CLI example: .. code-block:: bash salt myminion boto_elb.delete_policy myelb mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not exists(name, region, key, keyid, profile): return True try: conn.delete_lb_policy(name, policy_name) log.info('Deleted policy %s on ELB %s', policy_name, name) return True except boto.exception.BotoServerError as e: log.error('Failed to delete policy %s on ELB %s: %s', policy_name, name, e.message, exc_info_on_loglevel=logging.DEBUG) return False def set_listener_policy(name, port, policies=None, region=None, key=None, keyid=None, profile=None): ''' Set the policies of an ELB listener. .. versionadded:: 2016.3.0 CLI example: .. code-block:: Bash salt myminion boto_elb.set_listener_policy myelb 443 "[policy1,policy2]" ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not exists(name, region, key, keyid, profile): return True if policies is None: policies = [] try: conn.set_lb_policies_of_listener(name, port, policies) log.info('Set policies %s on ELB %s listener %s', policies, name, port) except boto.exception.BotoServerError as e: log.info('Failed to set policy %s on ELB %s listener %s: %s', policies, name, port, e.message, exc_info_on_loglevel=logging.DEBUG) return False return True def set_backend_policy(name, port, policies=None, region=None, key=None, keyid=None, profile=None): ''' Set the policies of an ELB backend server. CLI example: salt myminion boto_elb.set_backend_policy myelb 443 "[policy1,policy2]" ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not exists(name, region, key, keyid, profile): return True if policies is None: policies = [] try: conn.set_lb_policies_of_backend_server(name, port, policies) log.info('Set policies %s on ELB %s backend server %s', policies, name, port) except boto.exception.BotoServerError as e: log.info('Failed to set policy %s on ELB %s backend server %s: %s', policies, name, port, e.message, exc_info_on_loglevel=logging.DEBUG) return False return True def set_tags(name, tags, region=None, key=None, keyid=None, profile=None): ''' Add the tags on an ELB .. versionadded:: 2016.3.0 name name of the ELB tags dict of name/value pair tags CLI Example: .. code-block:: bash salt myminion boto_elb.set_tags my-elb-name "{'Tag1': 'Value', 'Tag2': 'Another Value'}" ''' if exists(name, region, key, keyid, profile): conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) ret = _add_tags(conn, name, tags) return ret else: return False def delete_tags(name, tags, region=None, key=None, keyid=None, profile=None): ''' Add the tags on an ELB name name of the ELB tags list of tags to remove CLI Example: .. code-block:: bash salt myminion boto_elb.delete_tags my-elb-name ['TagToRemove1', 'TagToRemove2'] ''' if exists(name, region, key, keyid, profile): conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) ret = _remove_tags(conn, name, tags) return ret else: return False def _build_tag_param_list(params, tags): ''' helper function to build a tag parameter list to send ''' keys = sorted(tags.keys()) i = 1 for key in keys: value = tags[key] params['Tags.member.{0}.Key'.format(i)] = key if value is not None: params['Tags.member.{0}.Value'.format(i)] = value i += 1 def _get_all_tags(conn, load_balancer_names=None): ''' Retrieve all the metadata tags associated with your ELB(s). :type load_balancer_names: list :param load_balancer_names: An optional list of load balancer names. :rtype: list :return: A list of :class:`boto.ec2.elb.tag.Tag` objects ''' params = {} if load_balancer_names: conn.build_list_params(params, load_balancer_names, 'LoadBalancerNames.member.%d') tags = conn.get_object( 'DescribeTags', params, __utils__['boto_elb_tag.get_tag_descriptions'](), verb='POST' ) if tags[load_balancer_names]: return tags[load_balancer_names] else: return None def _add_tags(conn, load_balancer_names, tags): ''' Create new metadata tags for the specified resource ids. :type load_balancer_names: list :param load_balancer_names: A list of load balancer names. :type tags: dict :param tags: A dictionary containing the name/value pairs. If you want to create only a tag name, the value for that tag should be the empty string (e.g. ''). ''' params = {} conn.build_list_params(params, load_balancer_names, 'LoadBalancerNames.member.%d') _build_tag_param_list(params, tags) return conn.get_status('AddTags', params, verb='POST') def _remove_tags(conn, load_balancer_names, tags): ''' Delete metadata tags for the specified resource ids. :type load_balancer_names: list :param load_balancer_names: A list of load balancer names. :type tags: list :param tags: A list containing just tag names for the tags to be deleted. ''' params = {} conn.build_list_params(params, load_balancer_names, 'LoadBalancerNames.member.%d') conn.build_list_params(params, tags, 'Tags.member.%d.Key') return conn.get_status('RemoveTags', params, verb='POST')
saltstack/salt
salt/modules/boto_elb.py
set_attributes
python
def set_attributes(name, attributes, region=None, key=None, keyid=None, profile=None): ''' Set attributes on an ELB. name (string) Name of the ELB instance to set attributes for attributes A dict of attributes to set. Valid attributes are: access_log (dict) enabled (bool) Enable storage of access logs. s3_bucket_name (string) The name of the S3 bucket to place logs. s3_bucket_prefix (string) Prefix for the log file name. emit_interval (int) Interval for storing logs in S3 in minutes. Valid values are 5 and 60. connection_draining (dict) enabled (bool) Enable connection draining. timeout (int) Maximum allowed time in seconds for sending existing connections to an instance that is deregistering or unhealthy. Default is 300. cross_zone_load_balancing (dict) enabled (bool) Enable cross-zone load balancing. CLI example to set attributes on an ELB: .. code-block:: bash salt myminion boto_elb.set_attributes myelb '{"access_log": {"enabled": "true", "s3_bucket_name": "mybucket", "s3_bucket_prefix": "mylogs/", "emit_interval": "5"}}' region=us-east-1 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) al = attributes.get('access_log', {}) czlb = attributes.get('cross_zone_load_balancing', {}) cd = attributes.get('connection_draining', {}) cs = attributes.get('connecting_settings', {}) if not al and not czlb and not cd and not cs: log.error('No supported attributes for ELB.') return False if al: _al = AccessLogAttribute() _al.enabled = al.get('enabled', False) if not _al.enabled: msg = 'Access log attribute configured, but enabled config missing' log.error(msg) return False _al.s3_bucket_name = al.get('s3_bucket_name', None) _al.s3_bucket_prefix = al.get('s3_bucket_prefix', None) _al.emit_interval = al.get('emit_interval', None) added_attr = conn.modify_lb_attribute(name, 'accessLog', _al) if added_attr: log.info('Added access_log attribute to %s elb.', name) else: log.error('Failed to add access_log attribute to %s elb.', name) return False if czlb: _czlb = CrossZoneLoadBalancingAttribute() _czlb.enabled = czlb['enabled'] added_attr = conn.modify_lb_attribute(name, 'crossZoneLoadBalancing', _czlb.enabled) if added_attr: log.info('Added cross_zone_load_balancing attribute to %s elb.', name) else: log.error('Failed to add cross_zone_load_balancing attribute.') return False if cd: _cd = ConnectionDrainingAttribute() _cd.enabled = cd['enabled'] _cd.timeout = cd.get('timeout', 300) added_attr = conn.modify_lb_attribute(name, 'connectionDraining', _cd) if added_attr: log.info('Added connection_draining attribute to %s elb.', name) else: log.error('Failed to add connection_draining attribute.') return False if cs: _cs = ConnectionSettingAttribute() _cs.idle_timeout = cs.get('idle_timeout', 60) added_attr = conn.modify_lb_attribute(name, 'connectingSettings', _cs) if added_attr: log.info('Added connecting_settings attribute to %s elb.', name) else: log.error('Failed to add connecting_settings attribute.') return False return True
Set attributes on an ELB. name (string) Name of the ELB instance to set attributes for attributes A dict of attributes to set. Valid attributes are: access_log (dict) enabled (bool) Enable storage of access logs. s3_bucket_name (string) The name of the S3 bucket to place logs. s3_bucket_prefix (string) Prefix for the log file name. emit_interval (int) Interval for storing logs in S3 in minutes. Valid values are 5 and 60. connection_draining (dict) enabled (bool) Enable connection draining. timeout (int) Maximum allowed time in seconds for sending existing connections to an instance that is deregistering or unhealthy. Default is 300. cross_zone_load_balancing (dict) enabled (bool) Enable cross-zone load balancing. CLI example to set attributes on an ELB: .. code-block:: bash salt myminion boto_elb.set_attributes myelb '{"access_log": {"enabled": "true", "s3_bucket_name": "mybucket", "s3_bucket_prefix": "mylogs/", "emit_interval": "5"}}' region=us-east-1
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_elb.py#L527-L623
null
# -*- coding: utf-8 -*- ''' Connection module for Amazon ELB .. versionadded:: 2014.7.0 :configuration: This module accepts explicit elb credentials but can also utilize IAM roles assigned to the instance through Instance Profiles. Dynamic credentials are then automatically obtained from AWS API and no further configuration is necessary. More Information available at: .. code-block:: text http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/iam-roles-for-amazon-ec2.html If IAM roles are not used you need to specify them either in a pillar or in the minion's config file: .. code-block:: yaml elb.keyid: GKTADJGHEIQSXMKKRBJ08H elb.key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs A region may also be specified in the configuration: .. code-block:: yaml elb.region: us-east-1 If a region is not specified, the default is us-east-1. It's also possible to specify key, keyid and region via a profile, either as a passed in dict, or as a string to pull from pillars or minion config: .. code-block:: yaml myprofile: keyid: GKTADJGHEIQSXMKKRBJ08H key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs region: us-east-1 :depends: boto >= 2.33.0 ''' # keep lint from choking on _get_conn and _cache_id # pylint: disable=E0602 from __future__ import absolute_import, print_function, unicode_literals # Import Python libs import logging import time log = logging.getLogger(__name__) # Import Salt libs import salt.utils.json import salt.utils.odict as odict import salt.utils.versions # Import third party libs from salt.ext import six try: import boto import boto.ec2 # pylint: enable=unused-import from boto.ec2.elb import HealthCheck from boto.ec2.elb.attributes import AccessLogAttribute from boto.ec2.elb.attributes import ConnectionDrainingAttribute from boto.ec2.elb.attributes import ConnectionSettingAttribute from boto.ec2.elb.attributes import CrossZoneLoadBalancingAttribute logging.getLogger('boto').setLevel(logging.CRITICAL) HAS_BOTO = True except ImportError: HAS_BOTO = False def __virtual__(): ''' Only load if boto libraries exist. ''' # connection settings were added in 2.33.0 has_boto_reqs = salt.utils.versions.check_boto_reqs( boto_ver='2.33.0', check_boto3=False ) if has_boto_reqs is True: __utils__['boto.assign_funcs'](__name__, 'elb', module='ec2.elb', pack=__salt__) return has_boto_reqs def exists(name, region=None, key=None, keyid=None, profile=None): ''' Check to see if an ELB exists. CLI example: .. code-block:: bash salt myminion boto_elb.exists myelb region=us-east-1 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: elb = conn.get_all_load_balancers(load_balancer_names=[name]) if elb: return True else: log.debug('The load balancer does not exist in region %s', region) return False except boto.exception.BotoServerError as error: log.warning(error) return False def get_all_elbs(region=None, key=None, keyid=None, profile=None): ''' Return all load balancers associated with an account CLI example: .. code-block:: bash salt myminion boto_elb.get_all_elbs region=us-east-1 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: return [e for e in conn.get_all_load_balancers()] except boto.exception.BotoServerError as error: log.warning(error) return [] def list_elbs(region=None, key=None, keyid=None, profile=None): ''' Return names of all load balancers associated with an account CLI example: .. code-block:: bash salt myminion boto_elb.list_elbs region=us-east-1 ''' return [e.name for e in get_all_elbs(region=region, key=key, keyid=keyid, profile=profile)] def get_elb_config(name, region=None, key=None, keyid=None, profile=None): ''' Get an ELB configuration. CLI example: .. code-block:: bash salt myminion boto_elb.exists myelb region=us-east-1 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) retries = 30 while retries: try: lb = conn.get_all_load_balancers(load_balancer_names=[name]) lb = lb[0] ret = {} ret['availability_zones'] = lb.availability_zones listeners = [] for _listener in lb.listeners: listener_dict = {} listener_dict['elb_port'] = _listener.load_balancer_port listener_dict['elb_protocol'] = _listener.protocol listener_dict['instance_port'] = _listener.instance_port listener_dict['instance_protocol'] = _listener.instance_protocol listener_dict['policies'] = _listener.policy_names if _listener.ssl_certificate_id: listener_dict['certificate'] = _listener.ssl_certificate_id listeners.append(listener_dict) ret['listeners'] = listeners backends = [] for _backend in lb.backends: bs_dict = {} bs_dict['instance_port'] = _backend.instance_port bs_dict['policies'] = [p.policy_name for p in _backend.policies] backends.append(bs_dict) ret['backends'] = backends ret['subnets'] = lb.subnets ret['security_groups'] = lb.security_groups ret['scheme'] = lb.scheme ret['dns_name'] = lb.dns_name ret['tags'] = _get_all_tags(conn, name) lb_policy_lists = [ lb.policies.app_cookie_stickiness_policies, lb.policies.lb_cookie_stickiness_policies, lb.policies.other_policies ] policies = [] for policy_list in lb_policy_lists: policies += [p.policy_name for p in policy_list] ret['policies'] = policies return ret except boto.exception.BotoServerError as error: if error.error_code == 'Throttling': log.debug('Throttled by AWS API, will retry in 5 seconds.') time.sleep(5) retries -= 1 continue log.error('Error fetching config for ELB %s: %s', name, error.message) log.error(error) return {} return {} def listener_dict_to_tuple(listener): ''' Convert an ELB listener dict into a listener tuple used by certain parts of the AWS ELB API. CLI example: .. code-block:: bash salt myminion boto_elb.listener_dict_to_tuple '{"elb_port":80,"instance_port":80,"elb_protocol":"HTTP"}' ''' # We define all listeners as complex listeners. if 'instance_protocol' not in listener: instance_protocol = listener['elb_protocol'].upper() else: instance_protocol = listener['instance_protocol'].upper() listener_tuple = [listener['elb_port'], listener['instance_port'], listener['elb_protocol'], instance_protocol] if 'certificate' in listener: listener_tuple.append(listener['certificate']) return tuple(listener_tuple) def create(name, availability_zones, listeners, subnets=None, security_groups=None, scheme='internet-facing', region=None, key=None, keyid=None, profile=None): ''' Create an ELB CLI example to create an ELB: .. code-block:: bash salt myminion boto_elb.create myelb '["us-east-1a", "us-east-1e"]' '{"elb_port": 443, "elb_protocol": "HTTPS", ...}' region=us-east-1 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if exists(name, region, key, keyid, profile): return True if isinstance(availability_zones, six.string_types): availability_zones = salt.utils.json.loads(availability_zones) if isinstance(listeners, six.string_types): listeners = salt.utils.json.loads(listeners) _complex_listeners = [] for listener in listeners: _complex_listeners.append(listener_dict_to_tuple(listener)) try: lb = conn.create_load_balancer(name=name, zones=availability_zones, subnets=subnets, security_groups=security_groups, scheme=scheme, complex_listeners=_complex_listeners) if lb: log.info('Created ELB %s', name) return True else: log.error('Failed to create ELB %s', name) return False except boto.exception.BotoServerError as error: log.error('Failed to create ELB %s: %s: %s', name, error.error_code, error.message, exc_info_on_loglevel=logging.DEBUG) return False def delete(name, region=None, key=None, keyid=None, profile=None): ''' Delete an ELB. CLI example to delete an ELB: .. code-block:: bash salt myminion boto_elb.delete myelb region=us-east-1 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not exists(name, region, key, keyid, profile): return True try: conn.delete_load_balancer(name) log.info('Deleted ELB %s.', name) return True except boto.exception.BotoServerError as error: log.error('Failed to delete ELB %s', name, exc_info_on_loglevel=logging.DEBUG) return False def create_listeners(name, listeners, region=None, key=None, keyid=None, profile=None): ''' Create listeners on an ELB. CLI example: .. code-block:: bash salt myminion boto_elb.create_listeners myelb '[["HTTPS", "HTTP", 443, 80, "arn:aws:iam::11 11111:server-certificate/mycert"]]' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if isinstance(listeners, six.string_types): listeners = salt.utils.json.loads(listeners) _complex_listeners = [] for listener in listeners: _complex_listeners.append(listener_dict_to_tuple(listener)) try: conn.create_load_balancer_listeners(name, [], _complex_listeners) log.info('Created ELB listeners on %s', name) return True except boto.exception.BotoServerError as error: log.error('Failed to create ELB listeners on %s: %s', name, error, exc_info_on_loglevel=logging.DEBUG) return False def delete_listeners(name, ports, region=None, key=None, keyid=None, profile=None): ''' Delete listeners on an ELB. CLI example: .. code-block:: bash salt myminion boto_elb.delete_listeners myelb '[80,443]' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if isinstance(ports, six.string_types): ports = salt.utils.json.loads(ports) try: conn.delete_load_balancer_listeners(name, ports) log.info('Deleted ELB listeners on %s', name) return True except boto.exception.BotoServerError as error: log.error('Failed to delete ELB listeners on %s: %s', name, error, exc_info_on_loglevel=logging.DEBUG) return False def apply_security_groups(name, security_groups, region=None, key=None, keyid=None, profile=None): ''' Apply security groups to ELB. CLI example: .. code-block:: bash salt myminion boto_elb.apply_security_groups myelb '["mysecgroup1"]' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if isinstance(security_groups, six.string_types): security_groups = salt.utils.json.loads(security_groups) try: conn.apply_security_groups_to_lb(name, security_groups) log.info('Applied security_groups on ELB %s', name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to appply security_groups on ELB %s: %s', name, e.message) return False def enable_availability_zones(name, availability_zones, region=None, key=None, keyid=None, profile=None): ''' Enable availability zones for ELB. CLI example: .. code-block:: bash salt myminion boto_elb.enable_availability_zones myelb '["us-east-1a"]' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if isinstance(availability_zones, six.string_types): availability_zones = salt.utils.json.loads(availability_zones) try: conn.enable_availability_zones(name, availability_zones) log.info('Enabled availability_zones on ELB %s', name) return True except boto.exception.BotoServerError as error: log.error('Failed to enable availability_zones on ELB %s: %s', name, error) return False def disable_availability_zones(name, availability_zones, region=None, key=None, keyid=None, profile=None): ''' Disable availability zones for ELB. CLI example: .. code-block:: bash salt myminion boto_elb.disable_availability_zones myelb '["us-east-1a"]' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if isinstance(availability_zones, six.string_types): availability_zones = salt.utils.json.loads(availability_zones) try: conn.disable_availability_zones(name, availability_zones) log.info('Disabled availability_zones on ELB %s', name) return True except boto.exception.BotoServerError as error: log.error('Failed to disable availability_zones on ELB %s: %s', name, error, exc_info_on_loglevel=logging.DEBUG) return False def attach_subnets(name, subnets, region=None, key=None, keyid=None, profile=None): ''' Attach ELB to subnets. CLI example: .. code-block:: bash salt myminion boto_elb.attach_subnets myelb '["mysubnet"]' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if isinstance(subnets, six.string_types): subnets = salt.utils.json.loads(subnets) try: conn.attach_lb_to_subnets(name, subnets) log.info('Attached ELB %s on subnets.', name) return True except boto.exception.BotoServerError as error: log.error('Failed to attach ELB %s on subnets: %s', name, error, exc_info_on_loglevel=logging.DEBUG) return False def detach_subnets(name, subnets, region=None, key=None, keyid=None, profile=None): ''' Detach ELB from subnets. CLI example: .. code-block:: bash salt myminion boto_elb.detach_subnets myelb '["mysubnet"]' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if isinstance(subnets, six.string_types): subnets = salt.utils.json.loads(subnets) try: conn.detach_lb_from_subnets(name, subnets) log.info('Detached ELB %s from subnets.', name) return True except boto.exception.BotoServerError as error: log.error('Failed to detach ELB %s from subnets: %s', name, error, exc_info_on_loglevel=logging.DEBUG) return False def get_attributes(name, region=None, key=None, keyid=None, profile=None): ''' Check to see if attributes are set on an ELB. CLI example: .. code-block:: bash salt myminion boto_elb.get_attributes myelb ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) retries = 30 while retries: try: lbattrs = conn.get_all_lb_attributes(name) ret = odict.OrderedDict() ret['access_log'] = odict.OrderedDict() ret['cross_zone_load_balancing'] = odict.OrderedDict() ret['connection_draining'] = odict.OrderedDict() ret['connecting_settings'] = odict.OrderedDict() al = lbattrs.access_log czlb = lbattrs.cross_zone_load_balancing cd = lbattrs.connection_draining cs = lbattrs.connecting_settings ret['access_log']['enabled'] = al.enabled ret['access_log']['s3_bucket_name'] = al.s3_bucket_name ret['access_log']['s3_bucket_prefix'] = al.s3_bucket_prefix ret['access_log']['emit_interval'] = al.emit_interval ret['cross_zone_load_balancing']['enabled'] = czlb.enabled ret['connection_draining']['enabled'] = cd.enabled ret['connection_draining']['timeout'] = cd.timeout ret['connecting_settings']['idle_timeout'] = cs.idle_timeout return ret except boto.exception.BotoServerError as e: if e.error_code == 'Throttling': log.debug("Throttled by AWS API, will retry in 5 seconds...") time.sleep(5) retries -= 1 continue log.error('ELB %s does not exist: %s', name, e.message) return {} return {} def get_health_check(name, region=None, key=None, keyid=None, profile=None): ''' Get the health check configured for this ELB. CLI example: .. code-block:: bash salt myminion boto_elb.get_health_check myelb ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) retries = 30 while True: try: lb = conn.get_all_load_balancers(load_balancer_names=[name]) lb = lb[0] ret = odict.OrderedDict() hc = lb.health_check ret['interval'] = hc.interval ret['target'] = hc.target ret['healthy_threshold'] = hc.healthy_threshold ret['timeout'] = hc.timeout ret['unhealthy_threshold'] = hc.unhealthy_threshold return ret except boto.exception.BotoServerError as e: if retries and e.code == 'Throttling': log.debug('Throttled by AWS API, will retry in 5 seconds.') time.sleep(5) retries -= 1 continue log.error('ELB %s not found.', name, exc_info_on_logleve=logging.DEBUG) return {} def set_health_check(name, health_check, region=None, key=None, keyid=None, profile=None): ''' Set attributes on an ELB. CLI example to set attributes on an ELB: .. code-block:: bash salt myminion boto_elb.set_health_check myelb '{"target": "HTTP:80/"}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) retries = 30 hc = HealthCheck(**health_check) while True: try: conn.configure_health_check(name, hc) log.info('Configured health check on ELB %s', name) return True except boto.exception.BotoServerError as error: if retries and e.code == 'Throttling': log.debug('Throttled by AWS API, will retry in 5 seconds.') time.sleep(5) retries -= 1 continue log.exception('Failed to configure health check on ELB %s', name) return False def register_instances(name, instances, region=None, key=None, keyid=None, profile=None): ''' Register instances with an ELB. Instances is either a string instance id or a list of string instance id's. Returns: - ``True``: instance(s) registered successfully - ``False``: instance(s) failed to be registered CLI example: .. code-block:: bash salt myminion boto_elb.register_instances myelb instance_id salt myminion boto_elb.register_instances myelb "[instance_id,instance_id]" ''' # convert instances to list type, enabling consistent use of instances # variable throughout the register_instances method if isinstance(instances, six.string_types) or isinstance(instances, six.text_type): instances = [instances] conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: registered_instances = conn.register_instances(name, instances) except boto.exception.BotoServerError as error: log.warning(error) return False registered_instance_ids = [instance.id for instance in registered_instances] # register_failues is a set that will contain any instances that were not # able to be registered with the given ELB register_failures = set(instances).difference(set(registered_instance_ids)) if register_failures: log.warning('Instance(s): %s not registered with ELB %s.', list(register_failures), name) register_result = False else: register_result = True return register_result def deregister_instances(name, instances, region=None, key=None, keyid=None, profile=None): ''' Deregister instances with an ELB. Instances is either a string instance id or a list of string instance id's. Returns: - ``True``: instance(s) deregistered successfully - ``False``: instance(s) failed to be deregistered - ``None``: instance(s) not valid or not registered, no action taken CLI example: .. code-block:: bash salt myminion boto_elb.deregister_instances myelb instance_id salt myminion boto_elb.deregister_instances myelb "[instance_id, instance_id]" ''' # convert instances to list type, enabling consistent use of instances # variable throughout the deregister_instances method if isinstance(instances, six.string_types) or isinstance(instances, six.text_type): instances = [instances] conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: registered_instances = conn.deregister_instances(name, instances) except boto.exception.BotoServerError as error: # if the instance(s) given as an argument are not members of the ELB # boto returns error.error_code == 'InvalidInstance' # deregister_instances returns "None" because the instances are # effectively deregistered from ELB if error.error_code == 'InvalidInstance': log.warning( 'One or more of instance(s) %s are not part of ELB %s. ' 'deregister_instances not performed.', instances, name ) return None else: log.warning(error) return False registered_instance_ids = [instance.id for instance in registered_instances] # deregister_failures is a set that will contain any instances that were # unable to be deregistered from the given ELB deregister_failures = set(instances).intersection(set(registered_instance_ids)) if deregister_failures: log.warning( 'Instance(s): %s not deregistered from ELB %s.', list(deregister_failures), name ) deregister_result = False else: deregister_result = True return deregister_result def set_instances(name, instances, test=False, region=None, key=None, keyid=None, profile=None): ''' Set the instances assigned to an ELB to exactly the list given CLI example: .. code-block:: bash salt myminion boto_elb.set_instances myelb region=us-east-1 instances="[instance_id,instance_id]" ''' ret = True current = set([i['instance_id'] for i in get_instance_health(name, region, key, keyid, profile)]) desired = set(instances) add = desired - current remove = current - desired if test: return bool(add or remove) if remove: if deregister_instances(name, list(remove), region, key, keyid, profile) is False: ret = False if add: if register_instances(name, list(add), region, key, keyid, profile) is False: ret = False return ret def get_instance_health(name, region=None, key=None, keyid=None, profile=None, instances=None): ''' Get a list of instances and their health state CLI example: .. code-block:: bash salt myminion boto_elb.get_instance_health myelb salt myminion boto_elb.get_instance_health myelb region=us-east-1 instances="[instance_id,instance_id]" ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: instance_states = conn.describe_instance_health(name, instances) ret = [] for _instance in instance_states: ret.append({'instance_id': _instance.instance_id, 'description': _instance.description, 'state': _instance.state, 'reason_code': _instance.reason_code }) return ret except boto.exception.BotoServerError as error: log.debug(error) return [] def create_policy(name, policy_name, policy_type, policy, region=None, key=None, keyid=None, profile=None): ''' Create an ELB policy. .. versionadded:: 2016.3.0 CLI example: .. code-block:: bash salt myminion boto_elb.create_policy myelb mypolicy LBCookieStickinessPolicyType '{"CookieExpirationPeriod": 3600}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not exists(name, region, key, keyid, profile): return False try: success = conn.create_lb_policy(name, policy_name, policy_type, policy) if success: log.info('Created policy %s on ELB %s', policy_name, name) return True else: log.error('Failed to create policy %s on ELB %s', policy_name, name) return False except boto.exception.BotoServerError as e: log.error('Failed to create policy %s on ELB %s: %s', policy_name, name, e.message, exc_info_on_loglevel=logging.DEBUG) return False def delete_policy(name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Delete an ELB policy. .. versionadded:: 2016.3.0 CLI example: .. code-block:: bash salt myminion boto_elb.delete_policy myelb mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not exists(name, region, key, keyid, profile): return True try: conn.delete_lb_policy(name, policy_name) log.info('Deleted policy %s on ELB %s', policy_name, name) return True except boto.exception.BotoServerError as e: log.error('Failed to delete policy %s on ELB %s: %s', policy_name, name, e.message, exc_info_on_loglevel=logging.DEBUG) return False def set_listener_policy(name, port, policies=None, region=None, key=None, keyid=None, profile=None): ''' Set the policies of an ELB listener. .. versionadded:: 2016.3.0 CLI example: .. code-block:: Bash salt myminion boto_elb.set_listener_policy myelb 443 "[policy1,policy2]" ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not exists(name, region, key, keyid, profile): return True if policies is None: policies = [] try: conn.set_lb_policies_of_listener(name, port, policies) log.info('Set policies %s on ELB %s listener %s', policies, name, port) except boto.exception.BotoServerError as e: log.info('Failed to set policy %s on ELB %s listener %s: %s', policies, name, port, e.message, exc_info_on_loglevel=logging.DEBUG) return False return True def set_backend_policy(name, port, policies=None, region=None, key=None, keyid=None, profile=None): ''' Set the policies of an ELB backend server. CLI example: salt myminion boto_elb.set_backend_policy myelb 443 "[policy1,policy2]" ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not exists(name, region, key, keyid, profile): return True if policies is None: policies = [] try: conn.set_lb_policies_of_backend_server(name, port, policies) log.info('Set policies %s on ELB %s backend server %s', policies, name, port) except boto.exception.BotoServerError as e: log.info('Failed to set policy %s on ELB %s backend server %s: %s', policies, name, port, e.message, exc_info_on_loglevel=logging.DEBUG) return False return True def set_tags(name, tags, region=None, key=None, keyid=None, profile=None): ''' Add the tags on an ELB .. versionadded:: 2016.3.0 name name of the ELB tags dict of name/value pair tags CLI Example: .. code-block:: bash salt myminion boto_elb.set_tags my-elb-name "{'Tag1': 'Value', 'Tag2': 'Another Value'}" ''' if exists(name, region, key, keyid, profile): conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) ret = _add_tags(conn, name, tags) return ret else: return False def delete_tags(name, tags, region=None, key=None, keyid=None, profile=None): ''' Add the tags on an ELB name name of the ELB tags list of tags to remove CLI Example: .. code-block:: bash salt myminion boto_elb.delete_tags my-elb-name ['TagToRemove1', 'TagToRemove2'] ''' if exists(name, region, key, keyid, profile): conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) ret = _remove_tags(conn, name, tags) return ret else: return False def _build_tag_param_list(params, tags): ''' helper function to build a tag parameter list to send ''' keys = sorted(tags.keys()) i = 1 for key in keys: value = tags[key] params['Tags.member.{0}.Key'.format(i)] = key if value is not None: params['Tags.member.{0}.Value'.format(i)] = value i += 1 def _get_all_tags(conn, load_balancer_names=None): ''' Retrieve all the metadata tags associated with your ELB(s). :type load_balancer_names: list :param load_balancer_names: An optional list of load balancer names. :rtype: list :return: A list of :class:`boto.ec2.elb.tag.Tag` objects ''' params = {} if load_balancer_names: conn.build_list_params(params, load_balancer_names, 'LoadBalancerNames.member.%d') tags = conn.get_object( 'DescribeTags', params, __utils__['boto_elb_tag.get_tag_descriptions'](), verb='POST' ) if tags[load_balancer_names]: return tags[load_balancer_names] else: return None def _add_tags(conn, load_balancer_names, tags): ''' Create new metadata tags for the specified resource ids. :type load_balancer_names: list :param load_balancer_names: A list of load balancer names. :type tags: dict :param tags: A dictionary containing the name/value pairs. If you want to create only a tag name, the value for that tag should be the empty string (e.g. ''). ''' params = {} conn.build_list_params(params, load_balancer_names, 'LoadBalancerNames.member.%d') _build_tag_param_list(params, tags) return conn.get_status('AddTags', params, verb='POST') def _remove_tags(conn, load_balancer_names, tags): ''' Delete metadata tags for the specified resource ids. :type load_balancer_names: list :param load_balancer_names: A list of load balancer names. :type tags: list :param tags: A list containing just tag names for the tags to be deleted. ''' params = {} conn.build_list_params(params, load_balancer_names, 'LoadBalancerNames.member.%d') conn.build_list_params(params, tags, 'Tags.member.%d.Key') return conn.get_status('RemoveTags', params, verb='POST')
saltstack/salt
salt/modules/boto_elb.py
get_health_check
python
def get_health_check(name, region=None, key=None, keyid=None, profile=None): ''' Get the health check configured for this ELB. CLI example: .. code-block:: bash salt myminion boto_elb.get_health_check myelb ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) retries = 30 while True: try: lb = conn.get_all_load_balancers(load_balancer_names=[name]) lb = lb[0] ret = odict.OrderedDict() hc = lb.health_check ret['interval'] = hc.interval ret['target'] = hc.target ret['healthy_threshold'] = hc.healthy_threshold ret['timeout'] = hc.timeout ret['unhealthy_threshold'] = hc.unhealthy_threshold return ret except boto.exception.BotoServerError as e: if retries and e.code == 'Throttling': log.debug('Throttled by AWS API, will retry in 5 seconds.') time.sleep(5) retries -= 1 continue log.error('ELB %s not found.', name, exc_info_on_logleve=logging.DEBUG) return {}
Get the health check configured for this ELB. CLI example: .. code-block:: bash salt myminion boto_elb.get_health_check myelb
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_elb.py#L626-L659
null
# -*- coding: utf-8 -*- ''' Connection module for Amazon ELB .. versionadded:: 2014.7.0 :configuration: This module accepts explicit elb credentials but can also utilize IAM roles assigned to the instance through Instance Profiles. Dynamic credentials are then automatically obtained from AWS API and no further configuration is necessary. More Information available at: .. code-block:: text http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/iam-roles-for-amazon-ec2.html If IAM roles are not used you need to specify them either in a pillar or in the minion's config file: .. code-block:: yaml elb.keyid: GKTADJGHEIQSXMKKRBJ08H elb.key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs A region may also be specified in the configuration: .. code-block:: yaml elb.region: us-east-1 If a region is not specified, the default is us-east-1. It's also possible to specify key, keyid and region via a profile, either as a passed in dict, or as a string to pull from pillars or minion config: .. code-block:: yaml myprofile: keyid: GKTADJGHEIQSXMKKRBJ08H key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs region: us-east-1 :depends: boto >= 2.33.0 ''' # keep lint from choking on _get_conn and _cache_id # pylint: disable=E0602 from __future__ import absolute_import, print_function, unicode_literals # Import Python libs import logging import time log = logging.getLogger(__name__) # Import Salt libs import salt.utils.json import salt.utils.odict as odict import salt.utils.versions # Import third party libs from salt.ext import six try: import boto import boto.ec2 # pylint: enable=unused-import from boto.ec2.elb import HealthCheck from boto.ec2.elb.attributes import AccessLogAttribute from boto.ec2.elb.attributes import ConnectionDrainingAttribute from boto.ec2.elb.attributes import ConnectionSettingAttribute from boto.ec2.elb.attributes import CrossZoneLoadBalancingAttribute logging.getLogger('boto').setLevel(logging.CRITICAL) HAS_BOTO = True except ImportError: HAS_BOTO = False def __virtual__(): ''' Only load if boto libraries exist. ''' # connection settings were added in 2.33.0 has_boto_reqs = salt.utils.versions.check_boto_reqs( boto_ver='2.33.0', check_boto3=False ) if has_boto_reqs is True: __utils__['boto.assign_funcs'](__name__, 'elb', module='ec2.elb', pack=__salt__) return has_boto_reqs def exists(name, region=None, key=None, keyid=None, profile=None): ''' Check to see if an ELB exists. CLI example: .. code-block:: bash salt myminion boto_elb.exists myelb region=us-east-1 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: elb = conn.get_all_load_balancers(load_balancer_names=[name]) if elb: return True else: log.debug('The load balancer does not exist in region %s', region) return False except boto.exception.BotoServerError as error: log.warning(error) return False def get_all_elbs(region=None, key=None, keyid=None, profile=None): ''' Return all load balancers associated with an account CLI example: .. code-block:: bash salt myminion boto_elb.get_all_elbs region=us-east-1 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: return [e for e in conn.get_all_load_balancers()] except boto.exception.BotoServerError as error: log.warning(error) return [] def list_elbs(region=None, key=None, keyid=None, profile=None): ''' Return names of all load balancers associated with an account CLI example: .. code-block:: bash salt myminion boto_elb.list_elbs region=us-east-1 ''' return [e.name for e in get_all_elbs(region=region, key=key, keyid=keyid, profile=profile)] def get_elb_config(name, region=None, key=None, keyid=None, profile=None): ''' Get an ELB configuration. CLI example: .. code-block:: bash salt myminion boto_elb.exists myelb region=us-east-1 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) retries = 30 while retries: try: lb = conn.get_all_load_balancers(load_balancer_names=[name]) lb = lb[0] ret = {} ret['availability_zones'] = lb.availability_zones listeners = [] for _listener in lb.listeners: listener_dict = {} listener_dict['elb_port'] = _listener.load_balancer_port listener_dict['elb_protocol'] = _listener.protocol listener_dict['instance_port'] = _listener.instance_port listener_dict['instance_protocol'] = _listener.instance_protocol listener_dict['policies'] = _listener.policy_names if _listener.ssl_certificate_id: listener_dict['certificate'] = _listener.ssl_certificate_id listeners.append(listener_dict) ret['listeners'] = listeners backends = [] for _backend in lb.backends: bs_dict = {} bs_dict['instance_port'] = _backend.instance_port bs_dict['policies'] = [p.policy_name for p in _backend.policies] backends.append(bs_dict) ret['backends'] = backends ret['subnets'] = lb.subnets ret['security_groups'] = lb.security_groups ret['scheme'] = lb.scheme ret['dns_name'] = lb.dns_name ret['tags'] = _get_all_tags(conn, name) lb_policy_lists = [ lb.policies.app_cookie_stickiness_policies, lb.policies.lb_cookie_stickiness_policies, lb.policies.other_policies ] policies = [] for policy_list in lb_policy_lists: policies += [p.policy_name for p in policy_list] ret['policies'] = policies return ret except boto.exception.BotoServerError as error: if error.error_code == 'Throttling': log.debug('Throttled by AWS API, will retry in 5 seconds.') time.sleep(5) retries -= 1 continue log.error('Error fetching config for ELB %s: %s', name, error.message) log.error(error) return {} return {} def listener_dict_to_tuple(listener): ''' Convert an ELB listener dict into a listener tuple used by certain parts of the AWS ELB API. CLI example: .. code-block:: bash salt myminion boto_elb.listener_dict_to_tuple '{"elb_port":80,"instance_port":80,"elb_protocol":"HTTP"}' ''' # We define all listeners as complex listeners. if 'instance_protocol' not in listener: instance_protocol = listener['elb_protocol'].upper() else: instance_protocol = listener['instance_protocol'].upper() listener_tuple = [listener['elb_port'], listener['instance_port'], listener['elb_protocol'], instance_protocol] if 'certificate' in listener: listener_tuple.append(listener['certificate']) return tuple(listener_tuple) def create(name, availability_zones, listeners, subnets=None, security_groups=None, scheme='internet-facing', region=None, key=None, keyid=None, profile=None): ''' Create an ELB CLI example to create an ELB: .. code-block:: bash salt myminion boto_elb.create myelb '["us-east-1a", "us-east-1e"]' '{"elb_port": 443, "elb_protocol": "HTTPS", ...}' region=us-east-1 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if exists(name, region, key, keyid, profile): return True if isinstance(availability_zones, six.string_types): availability_zones = salt.utils.json.loads(availability_zones) if isinstance(listeners, six.string_types): listeners = salt.utils.json.loads(listeners) _complex_listeners = [] for listener in listeners: _complex_listeners.append(listener_dict_to_tuple(listener)) try: lb = conn.create_load_balancer(name=name, zones=availability_zones, subnets=subnets, security_groups=security_groups, scheme=scheme, complex_listeners=_complex_listeners) if lb: log.info('Created ELB %s', name) return True else: log.error('Failed to create ELB %s', name) return False except boto.exception.BotoServerError as error: log.error('Failed to create ELB %s: %s: %s', name, error.error_code, error.message, exc_info_on_loglevel=logging.DEBUG) return False def delete(name, region=None, key=None, keyid=None, profile=None): ''' Delete an ELB. CLI example to delete an ELB: .. code-block:: bash salt myminion boto_elb.delete myelb region=us-east-1 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not exists(name, region, key, keyid, profile): return True try: conn.delete_load_balancer(name) log.info('Deleted ELB %s.', name) return True except boto.exception.BotoServerError as error: log.error('Failed to delete ELB %s', name, exc_info_on_loglevel=logging.DEBUG) return False def create_listeners(name, listeners, region=None, key=None, keyid=None, profile=None): ''' Create listeners on an ELB. CLI example: .. code-block:: bash salt myminion boto_elb.create_listeners myelb '[["HTTPS", "HTTP", 443, 80, "arn:aws:iam::11 11111:server-certificate/mycert"]]' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if isinstance(listeners, six.string_types): listeners = salt.utils.json.loads(listeners) _complex_listeners = [] for listener in listeners: _complex_listeners.append(listener_dict_to_tuple(listener)) try: conn.create_load_balancer_listeners(name, [], _complex_listeners) log.info('Created ELB listeners on %s', name) return True except boto.exception.BotoServerError as error: log.error('Failed to create ELB listeners on %s: %s', name, error, exc_info_on_loglevel=logging.DEBUG) return False def delete_listeners(name, ports, region=None, key=None, keyid=None, profile=None): ''' Delete listeners on an ELB. CLI example: .. code-block:: bash salt myminion boto_elb.delete_listeners myelb '[80,443]' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if isinstance(ports, six.string_types): ports = salt.utils.json.loads(ports) try: conn.delete_load_balancer_listeners(name, ports) log.info('Deleted ELB listeners on %s', name) return True except boto.exception.BotoServerError as error: log.error('Failed to delete ELB listeners on %s: %s', name, error, exc_info_on_loglevel=logging.DEBUG) return False def apply_security_groups(name, security_groups, region=None, key=None, keyid=None, profile=None): ''' Apply security groups to ELB. CLI example: .. code-block:: bash salt myminion boto_elb.apply_security_groups myelb '["mysecgroup1"]' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if isinstance(security_groups, six.string_types): security_groups = salt.utils.json.loads(security_groups) try: conn.apply_security_groups_to_lb(name, security_groups) log.info('Applied security_groups on ELB %s', name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to appply security_groups on ELB %s: %s', name, e.message) return False def enable_availability_zones(name, availability_zones, region=None, key=None, keyid=None, profile=None): ''' Enable availability zones for ELB. CLI example: .. code-block:: bash salt myminion boto_elb.enable_availability_zones myelb '["us-east-1a"]' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if isinstance(availability_zones, six.string_types): availability_zones = salt.utils.json.loads(availability_zones) try: conn.enable_availability_zones(name, availability_zones) log.info('Enabled availability_zones on ELB %s', name) return True except boto.exception.BotoServerError as error: log.error('Failed to enable availability_zones on ELB %s: %s', name, error) return False def disable_availability_zones(name, availability_zones, region=None, key=None, keyid=None, profile=None): ''' Disable availability zones for ELB. CLI example: .. code-block:: bash salt myminion boto_elb.disable_availability_zones myelb '["us-east-1a"]' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if isinstance(availability_zones, six.string_types): availability_zones = salt.utils.json.loads(availability_zones) try: conn.disable_availability_zones(name, availability_zones) log.info('Disabled availability_zones on ELB %s', name) return True except boto.exception.BotoServerError as error: log.error('Failed to disable availability_zones on ELB %s: %s', name, error, exc_info_on_loglevel=logging.DEBUG) return False def attach_subnets(name, subnets, region=None, key=None, keyid=None, profile=None): ''' Attach ELB to subnets. CLI example: .. code-block:: bash salt myminion boto_elb.attach_subnets myelb '["mysubnet"]' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if isinstance(subnets, six.string_types): subnets = salt.utils.json.loads(subnets) try: conn.attach_lb_to_subnets(name, subnets) log.info('Attached ELB %s on subnets.', name) return True except boto.exception.BotoServerError as error: log.error('Failed to attach ELB %s on subnets: %s', name, error, exc_info_on_loglevel=logging.DEBUG) return False def detach_subnets(name, subnets, region=None, key=None, keyid=None, profile=None): ''' Detach ELB from subnets. CLI example: .. code-block:: bash salt myminion boto_elb.detach_subnets myelb '["mysubnet"]' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if isinstance(subnets, six.string_types): subnets = salt.utils.json.loads(subnets) try: conn.detach_lb_from_subnets(name, subnets) log.info('Detached ELB %s from subnets.', name) return True except boto.exception.BotoServerError as error: log.error('Failed to detach ELB %s from subnets: %s', name, error, exc_info_on_loglevel=logging.DEBUG) return False def get_attributes(name, region=None, key=None, keyid=None, profile=None): ''' Check to see if attributes are set on an ELB. CLI example: .. code-block:: bash salt myminion boto_elb.get_attributes myelb ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) retries = 30 while retries: try: lbattrs = conn.get_all_lb_attributes(name) ret = odict.OrderedDict() ret['access_log'] = odict.OrderedDict() ret['cross_zone_load_balancing'] = odict.OrderedDict() ret['connection_draining'] = odict.OrderedDict() ret['connecting_settings'] = odict.OrderedDict() al = lbattrs.access_log czlb = lbattrs.cross_zone_load_balancing cd = lbattrs.connection_draining cs = lbattrs.connecting_settings ret['access_log']['enabled'] = al.enabled ret['access_log']['s3_bucket_name'] = al.s3_bucket_name ret['access_log']['s3_bucket_prefix'] = al.s3_bucket_prefix ret['access_log']['emit_interval'] = al.emit_interval ret['cross_zone_load_balancing']['enabled'] = czlb.enabled ret['connection_draining']['enabled'] = cd.enabled ret['connection_draining']['timeout'] = cd.timeout ret['connecting_settings']['idle_timeout'] = cs.idle_timeout return ret except boto.exception.BotoServerError as e: if e.error_code == 'Throttling': log.debug("Throttled by AWS API, will retry in 5 seconds...") time.sleep(5) retries -= 1 continue log.error('ELB %s does not exist: %s', name, e.message) return {} return {} def set_attributes(name, attributes, region=None, key=None, keyid=None, profile=None): ''' Set attributes on an ELB. name (string) Name of the ELB instance to set attributes for attributes A dict of attributes to set. Valid attributes are: access_log (dict) enabled (bool) Enable storage of access logs. s3_bucket_name (string) The name of the S3 bucket to place logs. s3_bucket_prefix (string) Prefix for the log file name. emit_interval (int) Interval for storing logs in S3 in minutes. Valid values are 5 and 60. connection_draining (dict) enabled (bool) Enable connection draining. timeout (int) Maximum allowed time in seconds for sending existing connections to an instance that is deregistering or unhealthy. Default is 300. cross_zone_load_balancing (dict) enabled (bool) Enable cross-zone load balancing. CLI example to set attributes on an ELB: .. code-block:: bash salt myminion boto_elb.set_attributes myelb '{"access_log": {"enabled": "true", "s3_bucket_name": "mybucket", "s3_bucket_prefix": "mylogs/", "emit_interval": "5"}}' region=us-east-1 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) al = attributes.get('access_log', {}) czlb = attributes.get('cross_zone_load_balancing', {}) cd = attributes.get('connection_draining', {}) cs = attributes.get('connecting_settings', {}) if not al and not czlb and not cd and not cs: log.error('No supported attributes for ELB.') return False if al: _al = AccessLogAttribute() _al.enabled = al.get('enabled', False) if not _al.enabled: msg = 'Access log attribute configured, but enabled config missing' log.error(msg) return False _al.s3_bucket_name = al.get('s3_bucket_name', None) _al.s3_bucket_prefix = al.get('s3_bucket_prefix', None) _al.emit_interval = al.get('emit_interval', None) added_attr = conn.modify_lb_attribute(name, 'accessLog', _al) if added_attr: log.info('Added access_log attribute to %s elb.', name) else: log.error('Failed to add access_log attribute to %s elb.', name) return False if czlb: _czlb = CrossZoneLoadBalancingAttribute() _czlb.enabled = czlb['enabled'] added_attr = conn.modify_lb_attribute(name, 'crossZoneLoadBalancing', _czlb.enabled) if added_attr: log.info('Added cross_zone_load_balancing attribute to %s elb.', name) else: log.error('Failed to add cross_zone_load_balancing attribute.') return False if cd: _cd = ConnectionDrainingAttribute() _cd.enabled = cd['enabled'] _cd.timeout = cd.get('timeout', 300) added_attr = conn.modify_lb_attribute(name, 'connectionDraining', _cd) if added_attr: log.info('Added connection_draining attribute to %s elb.', name) else: log.error('Failed to add connection_draining attribute.') return False if cs: _cs = ConnectionSettingAttribute() _cs.idle_timeout = cs.get('idle_timeout', 60) added_attr = conn.modify_lb_attribute(name, 'connectingSettings', _cs) if added_attr: log.info('Added connecting_settings attribute to %s elb.', name) else: log.error('Failed to add connecting_settings attribute.') return False return True def set_health_check(name, health_check, region=None, key=None, keyid=None, profile=None): ''' Set attributes on an ELB. CLI example to set attributes on an ELB: .. code-block:: bash salt myminion boto_elb.set_health_check myelb '{"target": "HTTP:80/"}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) retries = 30 hc = HealthCheck(**health_check) while True: try: conn.configure_health_check(name, hc) log.info('Configured health check on ELB %s', name) return True except boto.exception.BotoServerError as error: if retries and e.code == 'Throttling': log.debug('Throttled by AWS API, will retry in 5 seconds.') time.sleep(5) retries -= 1 continue log.exception('Failed to configure health check on ELB %s', name) return False def register_instances(name, instances, region=None, key=None, keyid=None, profile=None): ''' Register instances with an ELB. Instances is either a string instance id or a list of string instance id's. Returns: - ``True``: instance(s) registered successfully - ``False``: instance(s) failed to be registered CLI example: .. code-block:: bash salt myminion boto_elb.register_instances myelb instance_id salt myminion boto_elb.register_instances myelb "[instance_id,instance_id]" ''' # convert instances to list type, enabling consistent use of instances # variable throughout the register_instances method if isinstance(instances, six.string_types) or isinstance(instances, six.text_type): instances = [instances] conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: registered_instances = conn.register_instances(name, instances) except boto.exception.BotoServerError as error: log.warning(error) return False registered_instance_ids = [instance.id for instance in registered_instances] # register_failues is a set that will contain any instances that were not # able to be registered with the given ELB register_failures = set(instances).difference(set(registered_instance_ids)) if register_failures: log.warning('Instance(s): %s not registered with ELB %s.', list(register_failures), name) register_result = False else: register_result = True return register_result def deregister_instances(name, instances, region=None, key=None, keyid=None, profile=None): ''' Deregister instances with an ELB. Instances is either a string instance id or a list of string instance id's. Returns: - ``True``: instance(s) deregistered successfully - ``False``: instance(s) failed to be deregistered - ``None``: instance(s) not valid or not registered, no action taken CLI example: .. code-block:: bash salt myminion boto_elb.deregister_instances myelb instance_id salt myminion boto_elb.deregister_instances myelb "[instance_id, instance_id]" ''' # convert instances to list type, enabling consistent use of instances # variable throughout the deregister_instances method if isinstance(instances, six.string_types) or isinstance(instances, six.text_type): instances = [instances] conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: registered_instances = conn.deregister_instances(name, instances) except boto.exception.BotoServerError as error: # if the instance(s) given as an argument are not members of the ELB # boto returns error.error_code == 'InvalidInstance' # deregister_instances returns "None" because the instances are # effectively deregistered from ELB if error.error_code == 'InvalidInstance': log.warning( 'One or more of instance(s) %s are not part of ELB %s. ' 'deregister_instances not performed.', instances, name ) return None else: log.warning(error) return False registered_instance_ids = [instance.id for instance in registered_instances] # deregister_failures is a set that will contain any instances that were # unable to be deregistered from the given ELB deregister_failures = set(instances).intersection(set(registered_instance_ids)) if deregister_failures: log.warning( 'Instance(s): %s not deregistered from ELB %s.', list(deregister_failures), name ) deregister_result = False else: deregister_result = True return deregister_result def set_instances(name, instances, test=False, region=None, key=None, keyid=None, profile=None): ''' Set the instances assigned to an ELB to exactly the list given CLI example: .. code-block:: bash salt myminion boto_elb.set_instances myelb region=us-east-1 instances="[instance_id,instance_id]" ''' ret = True current = set([i['instance_id'] for i in get_instance_health(name, region, key, keyid, profile)]) desired = set(instances) add = desired - current remove = current - desired if test: return bool(add or remove) if remove: if deregister_instances(name, list(remove), region, key, keyid, profile) is False: ret = False if add: if register_instances(name, list(add), region, key, keyid, profile) is False: ret = False return ret def get_instance_health(name, region=None, key=None, keyid=None, profile=None, instances=None): ''' Get a list of instances and their health state CLI example: .. code-block:: bash salt myminion boto_elb.get_instance_health myelb salt myminion boto_elb.get_instance_health myelb region=us-east-1 instances="[instance_id,instance_id]" ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: instance_states = conn.describe_instance_health(name, instances) ret = [] for _instance in instance_states: ret.append({'instance_id': _instance.instance_id, 'description': _instance.description, 'state': _instance.state, 'reason_code': _instance.reason_code }) return ret except boto.exception.BotoServerError as error: log.debug(error) return [] def create_policy(name, policy_name, policy_type, policy, region=None, key=None, keyid=None, profile=None): ''' Create an ELB policy. .. versionadded:: 2016.3.0 CLI example: .. code-block:: bash salt myminion boto_elb.create_policy myelb mypolicy LBCookieStickinessPolicyType '{"CookieExpirationPeriod": 3600}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not exists(name, region, key, keyid, profile): return False try: success = conn.create_lb_policy(name, policy_name, policy_type, policy) if success: log.info('Created policy %s on ELB %s', policy_name, name) return True else: log.error('Failed to create policy %s on ELB %s', policy_name, name) return False except boto.exception.BotoServerError as e: log.error('Failed to create policy %s on ELB %s: %s', policy_name, name, e.message, exc_info_on_loglevel=logging.DEBUG) return False def delete_policy(name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Delete an ELB policy. .. versionadded:: 2016.3.0 CLI example: .. code-block:: bash salt myminion boto_elb.delete_policy myelb mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not exists(name, region, key, keyid, profile): return True try: conn.delete_lb_policy(name, policy_name) log.info('Deleted policy %s on ELB %s', policy_name, name) return True except boto.exception.BotoServerError as e: log.error('Failed to delete policy %s on ELB %s: %s', policy_name, name, e.message, exc_info_on_loglevel=logging.DEBUG) return False def set_listener_policy(name, port, policies=None, region=None, key=None, keyid=None, profile=None): ''' Set the policies of an ELB listener. .. versionadded:: 2016.3.0 CLI example: .. code-block:: Bash salt myminion boto_elb.set_listener_policy myelb 443 "[policy1,policy2]" ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not exists(name, region, key, keyid, profile): return True if policies is None: policies = [] try: conn.set_lb_policies_of_listener(name, port, policies) log.info('Set policies %s on ELB %s listener %s', policies, name, port) except boto.exception.BotoServerError as e: log.info('Failed to set policy %s on ELB %s listener %s: %s', policies, name, port, e.message, exc_info_on_loglevel=logging.DEBUG) return False return True def set_backend_policy(name, port, policies=None, region=None, key=None, keyid=None, profile=None): ''' Set the policies of an ELB backend server. CLI example: salt myminion boto_elb.set_backend_policy myelb 443 "[policy1,policy2]" ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not exists(name, region, key, keyid, profile): return True if policies is None: policies = [] try: conn.set_lb_policies_of_backend_server(name, port, policies) log.info('Set policies %s on ELB %s backend server %s', policies, name, port) except boto.exception.BotoServerError as e: log.info('Failed to set policy %s on ELB %s backend server %s: %s', policies, name, port, e.message, exc_info_on_loglevel=logging.DEBUG) return False return True def set_tags(name, tags, region=None, key=None, keyid=None, profile=None): ''' Add the tags on an ELB .. versionadded:: 2016.3.0 name name of the ELB tags dict of name/value pair tags CLI Example: .. code-block:: bash salt myminion boto_elb.set_tags my-elb-name "{'Tag1': 'Value', 'Tag2': 'Another Value'}" ''' if exists(name, region, key, keyid, profile): conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) ret = _add_tags(conn, name, tags) return ret else: return False def delete_tags(name, tags, region=None, key=None, keyid=None, profile=None): ''' Add the tags on an ELB name name of the ELB tags list of tags to remove CLI Example: .. code-block:: bash salt myminion boto_elb.delete_tags my-elb-name ['TagToRemove1', 'TagToRemove2'] ''' if exists(name, region, key, keyid, profile): conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) ret = _remove_tags(conn, name, tags) return ret else: return False def _build_tag_param_list(params, tags): ''' helper function to build a tag parameter list to send ''' keys = sorted(tags.keys()) i = 1 for key in keys: value = tags[key] params['Tags.member.{0}.Key'.format(i)] = key if value is not None: params['Tags.member.{0}.Value'.format(i)] = value i += 1 def _get_all_tags(conn, load_balancer_names=None): ''' Retrieve all the metadata tags associated with your ELB(s). :type load_balancer_names: list :param load_balancer_names: An optional list of load balancer names. :rtype: list :return: A list of :class:`boto.ec2.elb.tag.Tag` objects ''' params = {} if load_balancer_names: conn.build_list_params(params, load_balancer_names, 'LoadBalancerNames.member.%d') tags = conn.get_object( 'DescribeTags', params, __utils__['boto_elb_tag.get_tag_descriptions'](), verb='POST' ) if tags[load_balancer_names]: return tags[load_balancer_names] else: return None def _add_tags(conn, load_balancer_names, tags): ''' Create new metadata tags for the specified resource ids. :type load_balancer_names: list :param load_balancer_names: A list of load balancer names. :type tags: dict :param tags: A dictionary containing the name/value pairs. If you want to create only a tag name, the value for that tag should be the empty string (e.g. ''). ''' params = {} conn.build_list_params(params, load_balancer_names, 'LoadBalancerNames.member.%d') _build_tag_param_list(params, tags) return conn.get_status('AddTags', params, verb='POST') def _remove_tags(conn, load_balancer_names, tags): ''' Delete metadata tags for the specified resource ids. :type load_balancer_names: list :param load_balancer_names: A list of load balancer names. :type tags: list :param tags: A list containing just tag names for the tags to be deleted. ''' params = {} conn.build_list_params(params, load_balancer_names, 'LoadBalancerNames.member.%d') conn.build_list_params(params, tags, 'Tags.member.%d.Key') return conn.get_status('RemoveTags', params, verb='POST')
saltstack/salt
salt/modules/boto_elb.py
set_health_check
python
def set_health_check(name, health_check, region=None, key=None, keyid=None, profile=None): ''' Set attributes on an ELB. CLI example to set attributes on an ELB: .. code-block:: bash salt myminion boto_elb.set_health_check myelb '{"target": "HTTP:80/"}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) retries = 30 hc = HealthCheck(**health_check) while True: try: conn.configure_health_check(name, hc) log.info('Configured health check on ELB %s', name) return True except boto.exception.BotoServerError as error: if retries and e.code == 'Throttling': log.debug('Throttled by AWS API, will retry in 5 seconds.') time.sleep(5) retries -= 1 continue log.exception('Failed to configure health check on ELB %s', name) return False
Set attributes on an ELB. CLI example to set attributes on an ELB: .. code-block:: bash salt myminion boto_elb.set_health_check myelb '{"target": "HTTP:80/"}'
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_elb.py#L662-L689
null
# -*- coding: utf-8 -*- ''' Connection module for Amazon ELB .. versionadded:: 2014.7.0 :configuration: This module accepts explicit elb credentials but can also utilize IAM roles assigned to the instance through Instance Profiles. Dynamic credentials are then automatically obtained from AWS API and no further configuration is necessary. More Information available at: .. code-block:: text http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/iam-roles-for-amazon-ec2.html If IAM roles are not used you need to specify them either in a pillar or in the minion's config file: .. code-block:: yaml elb.keyid: GKTADJGHEIQSXMKKRBJ08H elb.key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs A region may also be specified in the configuration: .. code-block:: yaml elb.region: us-east-1 If a region is not specified, the default is us-east-1. It's also possible to specify key, keyid and region via a profile, either as a passed in dict, or as a string to pull from pillars or minion config: .. code-block:: yaml myprofile: keyid: GKTADJGHEIQSXMKKRBJ08H key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs region: us-east-1 :depends: boto >= 2.33.0 ''' # keep lint from choking on _get_conn and _cache_id # pylint: disable=E0602 from __future__ import absolute_import, print_function, unicode_literals # Import Python libs import logging import time log = logging.getLogger(__name__) # Import Salt libs import salt.utils.json import salt.utils.odict as odict import salt.utils.versions # Import third party libs from salt.ext import six try: import boto import boto.ec2 # pylint: enable=unused-import from boto.ec2.elb import HealthCheck from boto.ec2.elb.attributes import AccessLogAttribute from boto.ec2.elb.attributes import ConnectionDrainingAttribute from boto.ec2.elb.attributes import ConnectionSettingAttribute from boto.ec2.elb.attributes import CrossZoneLoadBalancingAttribute logging.getLogger('boto').setLevel(logging.CRITICAL) HAS_BOTO = True except ImportError: HAS_BOTO = False def __virtual__(): ''' Only load if boto libraries exist. ''' # connection settings were added in 2.33.0 has_boto_reqs = salt.utils.versions.check_boto_reqs( boto_ver='2.33.0', check_boto3=False ) if has_boto_reqs is True: __utils__['boto.assign_funcs'](__name__, 'elb', module='ec2.elb', pack=__salt__) return has_boto_reqs def exists(name, region=None, key=None, keyid=None, profile=None): ''' Check to see if an ELB exists. CLI example: .. code-block:: bash salt myminion boto_elb.exists myelb region=us-east-1 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: elb = conn.get_all_load_balancers(load_balancer_names=[name]) if elb: return True else: log.debug('The load balancer does not exist in region %s', region) return False except boto.exception.BotoServerError as error: log.warning(error) return False def get_all_elbs(region=None, key=None, keyid=None, profile=None): ''' Return all load balancers associated with an account CLI example: .. code-block:: bash salt myminion boto_elb.get_all_elbs region=us-east-1 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: return [e for e in conn.get_all_load_balancers()] except boto.exception.BotoServerError as error: log.warning(error) return [] def list_elbs(region=None, key=None, keyid=None, profile=None): ''' Return names of all load balancers associated with an account CLI example: .. code-block:: bash salt myminion boto_elb.list_elbs region=us-east-1 ''' return [e.name for e in get_all_elbs(region=region, key=key, keyid=keyid, profile=profile)] def get_elb_config(name, region=None, key=None, keyid=None, profile=None): ''' Get an ELB configuration. CLI example: .. code-block:: bash salt myminion boto_elb.exists myelb region=us-east-1 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) retries = 30 while retries: try: lb = conn.get_all_load_balancers(load_balancer_names=[name]) lb = lb[0] ret = {} ret['availability_zones'] = lb.availability_zones listeners = [] for _listener in lb.listeners: listener_dict = {} listener_dict['elb_port'] = _listener.load_balancer_port listener_dict['elb_protocol'] = _listener.protocol listener_dict['instance_port'] = _listener.instance_port listener_dict['instance_protocol'] = _listener.instance_protocol listener_dict['policies'] = _listener.policy_names if _listener.ssl_certificate_id: listener_dict['certificate'] = _listener.ssl_certificate_id listeners.append(listener_dict) ret['listeners'] = listeners backends = [] for _backend in lb.backends: bs_dict = {} bs_dict['instance_port'] = _backend.instance_port bs_dict['policies'] = [p.policy_name for p in _backend.policies] backends.append(bs_dict) ret['backends'] = backends ret['subnets'] = lb.subnets ret['security_groups'] = lb.security_groups ret['scheme'] = lb.scheme ret['dns_name'] = lb.dns_name ret['tags'] = _get_all_tags(conn, name) lb_policy_lists = [ lb.policies.app_cookie_stickiness_policies, lb.policies.lb_cookie_stickiness_policies, lb.policies.other_policies ] policies = [] for policy_list in lb_policy_lists: policies += [p.policy_name for p in policy_list] ret['policies'] = policies return ret except boto.exception.BotoServerError as error: if error.error_code == 'Throttling': log.debug('Throttled by AWS API, will retry in 5 seconds.') time.sleep(5) retries -= 1 continue log.error('Error fetching config for ELB %s: %s', name, error.message) log.error(error) return {} return {} def listener_dict_to_tuple(listener): ''' Convert an ELB listener dict into a listener tuple used by certain parts of the AWS ELB API. CLI example: .. code-block:: bash salt myminion boto_elb.listener_dict_to_tuple '{"elb_port":80,"instance_port":80,"elb_protocol":"HTTP"}' ''' # We define all listeners as complex listeners. if 'instance_protocol' not in listener: instance_protocol = listener['elb_protocol'].upper() else: instance_protocol = listener['instance_protocol'].upper() listener_tuple = [listener['elb_port'], listener['instance_port'], listener['elb_protocol'], instance_protocol] if 'certificate' in listener: listener_tuple.append(listener['certificate']) return tuple(listener_tuple) def create(name, availability_zones, listeners, subnets=None, security_groups=None, scheme='internet-facing', region=None, key=None, keyid=None, profile=None): ''' Create an ELB CLI example to create an ELB: .. code-block:: bash salt myminion boto_elb.create myelb '["us-east-1a", "us-east-1e"]' '{"elb_port": 443, "elb_protocol": "HTTPS", ...}' region=us-east-1 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if exists(name, region, key, keyid, profile): return True if isinstance(availability_zones, six.string_types): availability_zones = salt.utils.json.loads(availability_zones) if isinstance(listeners, six.string_types): listeners = salt.utils.json.loads(listeners) _complex_listeners = [] for listener in listeners: _complex_listeners.append(listener_dict_to_tuple(listener)) try: lb = conn.create_load_balancer(name=name, zones=availability_zones, subnets=subnets, security_groups=security_groups, scheme=scheme, complex_listeners=_complex_listeners) if lb: log.info('Created ELB %s', name) return True else: log.error('Failed to create ELB %s', name) return False except boto.exception.BotoServerError as error: log.error('Failed to create ELB %s: %s: %s', name, error.error_code, error.message, exc_info_on_loglevel=logging.DEBUG) return False def delete(name, region=None, key=None, keyid=None, profile=None): ''' Delete an ELB. CLI example to delete an ELB: .. code-block:: bash salt myminion boto_elb.delete myelb region=us-east-1 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not exists(name, region, key, keyid, profile): return True try: conn.delete_load_balancer(name) log.info('Deleted ELB %s.', name) return True except boto.exception.BotoServerError as error: log.error('Failed to delete ELB %s', name, exc_info_on_loglevel=logging.DEBUG) return False def create_listeners(name, listeners, region=None, key=None, keyid=None, profile=None): ''' Create listeners on an ELB. CLI example: .. code-block:: bash salt myminion boto_elb.create_listeners myelb '[["HTTPS", "HTTP", 443, 80, "arn:aws:iam::11 11111:server-certificate/mycert"]]' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if isinstance(listeners, six.string_types): listeners = salt.utils.json.loads(listeners) _complex_listeners = [] for listener in listeners: _complex_listeners.append(listener_dict_to_tuple(listener)) try: conn.create_load_balancer_listeners(name, [], _complex_listeners) log.info('Created ELB listeners on %s', name) return True except boto.exception.BotoServerError as error: log.error('Failed to create ELB listeners on %s: %s', name, error, exc_info_on_loglevel=logging.DEBUG) return False def delete_listeners(name, ports, region=None, key=None, keyid=None, profile=None): ''' Delete listeners on an ELB. CLI example: .. code-block:: bash salt myminion boto_elb.delete_listeners myelb '[80,443]' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if isinstance(ports, six.string_types): ports = salt.utils.json.loads(ports) try: conn.delete_load_balancer_listeners(name, ports) log.info('Deleted ELB listeners on %s', name) return True except boto.exception.BotoServerError as error: log.error('Failed to delete ELB listeners on %s: %s', name, error, exc_info_on_loglevel=logging.DEBUG) return False def apply_security_groups(name, security_groups, region=None, key=None, keyid=None, profile=None): ''' Apply security groups to ELB. CLI example: .. code-block:: bash salt myminion boto_elb.apply_security_groups myelb '["mysecgroup1"]' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if isinstance(security_groups, six.string_types): security_groups = salt.utils.json.loads(security_groups) try: conn.apply_security_groups_to_lb(name, security_groups) log.info('Applied security_groups on ELB %s', name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to appply security_groups on ELB %s: %s', name, e.message) return False def enable_availability_zones(name, availability_zones, region=None, key=None, keyid=None, profile=None): ''' Enable availability zones for ELB. CLI example: .. code-block:: bash salt myminion boto_elb.enable_availability_zones myelb '["us-east-1a"]' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if isinstance(availability_zones, six.string_types): availability_zones = salt.utils.json.loads(availability_zones) try: conn.enable_availability_zones(name, availability_zones) log.info('Enabled availability_zones on ELB %s', name) return True except boto.exception.BotoServerError as error: log.error('Failed to enable availability_zones on ELB %s: %s', name, error) return False def disable_availability_zones(name, availability_zones, region=None, key=None, keyid=None, profile=None): ''' Disable availability zones for ELB. CLI example: .. code-block:: bash salt myminion boto_elb.disable_availability_zones myelb '["us-east-1a"]' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if isinstance(availability_zones, six.string_types): availability_zones = salt.utils.json.loads(availability_zones) try: conn.disable_availability_zones(name, availability_zones) log.info('Disabled availability_zones on ELB %s', name) return True except boto.exception.BotoServerError as error: log.error('Failed to disable availability_zones on ELB %s: %s', name, error, exc_info_on_loglevel=logging.DEBUG) return False def attach_subnets(name, subnets, region=None, key=None, keyid=None, profile=None): ''' Attach ELB to subnets. CLI example: .. code-block:: bash salt myminion boto_elb.attach_subnets myelb '["mysubnet"]' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if isinstance(subnets, six.string_types): subnets = salt.utils.json.loads(subnets) try: conn.attach_lb_to_subnets(name, subnets) log.info('Attached ELB %s on subnets.', name) return True except boto.exception.BotoServerError as error: log.error('Failed to attach ELB %s on subnets: %s', name, error, exc_info_on_loglevel=logging.DEBUG) return False def detach_subnets(name, subnets, region=None, key=None, keyid=None, profile=None): ''' Detach ELB from subnets. CLI example: .. code-block:: bash salt myminion boto_elb.detach_subnets myelb '["mysubnet"]' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if isinstance(subnets, six.string_types): subnets = salt.utils.json.loads(subnets) try: conn.detach_lb_from_subnets(name, subnets) log.info('Detached ELB %s from subnets.', name) return True except boto.exception.BotoServerError as error: log.error('Failed to detach ELB %s from subnets: %s', name, error, exc_info_on_loglevel=logging.DEBUG) return False def get_attributes(name, region=None, key=None, keyid=None, profile=None): ''' Check to see if attributes are set on an ELB. CLI example: .. code-block:: bash salt myminion boto_elb.get_attributes myelb ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) retries = 30 while retries: try: lbattrs = conn.get_all_lb_attributes(name) ret = odict.OrderedDict() ret['access_log'] = odict.OrderedDict() ret['cross_zone_load_balancing'] = odict.OrderedDict() ret['connection_draining'] = odict.OrderedDict() ret['connecting_settings'] = odict.OrderedDict() al = lbattrs.access_log czlb = lbattrs.cross_zone_load_balancing cd = lbattrs.connection_draining cs = lbattrs.connecting_settings ret['access_log']['enabled'] = al.enabled ret['access_log']['s3_bucket_name'] = al.s3_bucket_name ret['access_log']['s3_bucket_prefix'] = al.s3_bucket_prefix ret['access_log']['emit_interval'] = al.emit_interval ret['cross_zone_load_balancing']['enabled'] = czlb.enabled ret['connection_draining']['enabled'] = cd.enabled ret['connection_draining']['timeout'] = cd.timeout ret['connecting_settings']['idle_timeout'] = cs.idle_timeout return ret except boto.exception.BotoServerError as e: if e.error_code == 'Throttling': log.debug("Throttled by AWS API, will retry in 5 seconds...") time.sleep(5) retries -= 1 continue log.error('ELB %s does not exist: %s', name, e.message) return {} return {} def set_attributes(name, attributes, region=None, key=None, keyid=None, profile=None): ''' Set attributes on an ELB. name (string) Name of the ELB instance to set attributes for attributes A dict of attributes to set. Valid attributes are: access_log (dict) enabled (bool) Enable storage of access logs. s3_bucket_name (string) The name of the S3 bucket to place logs. s3_bucket_prefix (string) Prefix for the log file name. emit_interval (int) Interval for storing logs in S3 in minutes. Valid values are 5 and 60. connection_draining (dict) enabled (bool) Enable connection draining. timeout (int) Maximum allowed time in seconds for sending existing connections to an instance that is deregistering or unhealthy. Default is 300. cross_zone_load_balancing (dict) enabled (bool) Enable cross-zone load balancing. CLI example to set attributes on an ELB: .. code-block:: bash salt myminion boto_elb.set_attributes myelb '{"access_log": {"enabled": "true", "s3_bucket_name": "mybucket", "s3_bucket_prefix": "mylogs/", "emit_interval": "5"}}' region=us-east-1 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) al = attributes.get('access_log', {}) czlb = attributes.get('cross_zone_load_balancing', {}) cd = attributes.get('connection_draining', {}) cs = attributes.get('connecting_settings', {}) if not al and not czlb and not cd and not cs: log.error('No supported attributes for ELB.') return False if al: _al = AccessLogAttribute() _al.enabled = al.get('enabled', False) if not _al.enabled: msg = 'Access log attribute configured, but enabled config missing' log.error(msg) return False _al.s3_bucket_name = al.get('s3_bucket_name', None) _al.s3_bucket_prefix = al.get('s3_bucket_prefix', None) _al.emit_interval = al.get('emit_interval', None) added_attr = conn.modify_lb_attribute(name, 'accessLog', _al) if added_attr: log.info('Added access_log attribute to %s elb.', name) else: log.error('Failed to add access_log attribute to %s elb.', name) return False if czlb: _czlb = CrossZoneLoadBalancingAttribute() _czlb.enabled = czlb['enabled'] added_attr = conn.modify_lb_attribute(name, 'crossZoneLoadBalancing', _czlb.enabled) if added_attr: log.info('Added cross_zone_load_balancing attribute to %s elb.', name) else: log.error('Failed to add cross_zone_load_balancing attribute.') return False if cd: _cd = ConnectionDrainingAttribute() _cd.enabled = cd['enabled'] _cd.timeout = cd.get('timeout', 300) added_attr = conn.modify_lb_attribute(name, 'connectionDraining', _cd) if added_attr: log.info('Added connection_draining attribute to %s elb.', name) else: log.error('Failed to add connection_draining attribute.') return False if cs: _cs = ConnectionSettingAttribute() _cs.idle_timeout = cs.get('idle_timeout', 60) added_attr = conn.modify_lb_attribute(name, 'connectingSettings', _cs) if added_attr: log.info('Added connecting_settings attribute to %s elb.', name) else: log.error('Failed to add connecting_settings attribute.') return False return True def get_health_check(name, region=None, key=None, keyid=None, profile=None): ''' Get the health check configured for this ELB. CLI example: .. code-block:: bash salt myminion boto_elb.get_health_check myelb ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) retries = 30 while True: try: lb = conn.get_all_load_balancers(load_balancer_names=[name]) lb = lb[0] ret = odict.OrderedDict() hc = lb.health_check ret['interval'] = hc.interval ret['target'] = hc.target ret['healthy_threshold'] = hc.healthy_threshold ret['timeout'] = hc.timeout ret['unhealthy_threshold'] = hc.unhealthy_threshold return ret except boto.exception.BotoServerError as e: if retries and e.code == 'Throttling': log.debug('Throttled by AWS API, will retry in 5 seconds.') time.sleep(5) retries -= 1 continue log.error('ELB %s not found.', name, exc_info_on_logleve=logging.DEBUG) return {} def register_instances(name, instances, region=None, key=None, keyid=None, profile=None): ''' Register instances with an ELB. Instances is either a string instance id or a list of string instance id's. Returns: - ``True``: instance(s) registered successfully - ``False``: instance(s) failed to be registered CLI example: .. code-block:: bash salt myminion boto_elb.register_instances myelb instance_id salt myminion boto_elb.register_instances myelb "[instance_id,instance_id]" ''' # convert instances to list type, enabling consistent use of instances # variable throughout the register_instances method if isinstance(instances, six.string_types) or isinstance(instances, six.text_type): instances = [instances] conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: registered_instances = conn.register_instances(name, instances) except boto.exception.BotoServerError as error: log.warning(error) return False registered_instance_ids = [instance.id for instance in registered_instances] # register_failues is a set that will contain any instances that were not # able to be registered with the given ELB register_failures = set(instances).difference(set(registered_instance_ids)) if register_failures: log.warning('Instance(s): %s not registered with ELB %s.', list(register_failures), name) register_result = False else: register_result = True return register_result def deregister_instances(name, instances, region=None, key=None, keyid=None, profile=None): ''' Deregister instances with an ELB. Instances is either a string instance id or a list of string instance id's. Returns: - ``True``: instance(s) deregistered successfully - ``False``: instance(s) failed to be deregistered - ``None``: instance(s) not valid or not registered, no action taken CLI example: .. code-block:: bash salt myminion boto_elb.deregister_instances myelb instance_id salt myminion boto_elb.deregister_instances myelb "[instance_id, instance_id]" ''' # convert instances to list type, enabling consistent use of instances # variable throughout the deregister_instances method if isinstance(instances, six.string_types) or isinstance(instances, six.text_type): instances = [instances] conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: registered_instances = conn.deregister_instances(name, instances) except boto.exception.BotoServerError as error: # if the instance(s) given as an argument are not members of the ELB # boto returns error.error_code == 'InvalidInstance' # deregister_instances returns "None" because the instances are # effectively deregistered from ELB if error.error_code == 'InvalidInstance': log.warning( 'One or more of instance(s) %s are not part of ELB %s. ' 'deregister_instances not performed.', instances, name ) return None else: log.warning(error) return False registered_instance_ids = [instance.id for instance in registered_instances] # deregister_failures is a set that will contain any instances that were # unable to be deregistered from the given ELB deregister_failures = set(instances).intersection(set(registered_instance_ids)) if deregister_failures: log.warning( 'Instance(s): %s not deregistered from ELB %s.', list(deregister_failures), name ) deregister_result = False else: deregister_result = True return deregister_result def set_instances(name, instances, test=False, region=None, key=None, keyid=None, profile=None): ''' Set the instances assigned to an ELB to exactly the list given CLI example: .. code-block:: bash salt myminion boto_elb.set_instances myelb region=us-east-1 instances="[instance_id,instance_id]" ''' ret = True current = set([i['instance_id'] for i in get_instance_health(name, region, key, keyid, profile)]) desired = set(instances) add = desired - current remove = current - desired if test: return bool(add or remove) if remove: if deregister_instances(name, list(remove), region, key, keyid, profile) is False: ret = False if add: if register_instances(name, list(add), region, key, keyid, profile) is False: ret = False return ret def get_instance_health(name, region=None, key=None, keyid=None, profile=None, instances=None): ''' Get a list of instances and their health state CLI example: .. code-block:: bash salt myminion boto_elb.get_instance_health myelb salt myminion boto_elb.get_instance_health myelb region=us-east-1 instances="[instance_id,instance_id]" ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: instance_states = conn.describe_instance_health(name, instances) ret = [] for _instance in instance_states: ret.append({'instance_id': _instance.instance_id, 'description': _instance.description, 'state': _instance.state, 'reason_code': _instance.reason_code }) return ret except boto.exception.BotoServerError as error: log.debug(error) return [] def create_policy(name, policy_name, policy_type, policy, region=None, key=None, keyid=None, profile=None): ''' Create an ELB policy. .. versionadded:: 2016.3.0 CLI example: .. code-block:: bash salt myminion boto_elb.create_policy myelb mypolicy LBCookieStickinessPolicyType '{"CookieExpirationPeriod": 3600}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not exists(name, region, key, keyid, profile): return False try: success = conn.create_lb_policy(name, policy_name, policy_type, policy) if success: log.info('Created policy %s on ELB %s', policy_name, name) return True else: log.error('Failed to create policy %s on ELB %s', policy_name, name) return False except boto.exception.BotoServerError as e: log.error('Failed to create policy %s on ELB %s: %s', policy_name, name, e.message, exc_info_on_loglevel=logging.DEBUG) return False def delete_policy(name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Delete an ELB policy. .. versionadded:: 2016.3.0 CLI example: .. code-block:: bash salt myminion boto_elb.delete_policy myelb mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not exists(name, region, key, keyid, profile): return True try: conn.delete_lb_policy(name, policy_name) log.info('Deleted policy %s on ELB %s', policy_name, name) return True except boto.exception.BotoServerError as e: log.error('Failed to delete policy %s on ELB %s: %s', policy_name, name, e.message, exc_info_on_loglevel=logging.DEBUG) return False def set_listener_policy(name, port, policies=None, region=None, key=None, keyid=None, profile=None): ''' Set the policies of an ELB listener. .. versionadded:: 2016.3.0 CLI example: .. code-block:: Bash salt myminion boto_elb.set_listener_policy myelb 443 "[policy1,policy2]" ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not exists(name, region, key, keyid, profile): return True if policies is None: policies = [] try: conn.set_lb_policies_of_listener(name, port, policies) log.info('Set policies %s on ELB %s listener %s', policies, name, port) except boto.exception.BotoServerError as e: log.info('Failed to set policy %s on ELB %s listener %s: %s', policies, name, port, e.message, exc_info_on_loglevel=logging.DEBUG) return False return True def set_backend_policy(name, port, policies=None, region=None, key=None, keyid=None, profile=None): ''' Set the policies of an ELB backend server. CLI example: salt myminion boto_elb.set_backend_policy myelb 443 "[policy1,policy2]" ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not exists(name, region, key, keyid, profile): return True if policies is None: policies = [] try: conn.set_lb_policies_of_backend_server(name, port, policies) log.info('Set policies %s on ELB %s backend server %s', policies, name, port) except boto.exception.BotoServerError as e: log.info('Failed to set policy %s on ELB %s backend server %s: %s', policies, name, port, e.message, exc_info_on_loglevel=logging.DEBUG) return False return True def set_tags(name, tags, region=None, key=None, keyid=None, profile=None): ''' Add the tags on an ELB .. versionadded:: 2016.3.0 name name of the ELB tags dict of name/value pair tags CLI Example: .. code-block:: bash salt myminion boto_elb.set_tags my-elb-name "{'Tag1': 'Value', 'Tag2': 'Another Value'}" ''' if exists(name, region, key, keyid, profile): conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) ret = _add_tags(conn, name, tags) return ret else: return False def delete_tags(name, tags, region=None, key=None, keyid=None, profile=None): ''' Add the tags on an ELB name name of the ELB tags list of tags to remove CLI Example: .. code-block:: bash salt myminion boto_elb.delete_tags my-elb-name ['TagToRemove1', 'TagToRemove2'] ''' if exists(name, region, key, keyid, profile): conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) ret = _remove_tags(conn, name, tags) return ret else: return False def _build_tag_param_list(params, tags): ''' helper function to build a tag parameter list to send ''' keys = sorted(tags.keys()) i = 1 for key in keys: value = tags[key] params['Tags.member.{0}.Key'.format(i)] = key if value is not None: params['Tags.member.{0}.Value'.format(i)] = value i += 1 def _get_all_tags(conn, load_balancer_names=None): ''' Retrieve all the metadata tags associated with your ELB(s). :type load_balancer_names: list :param load_balancer_names: An optional list of load balancer names. :rtype: list :return: A list of :class:`boto.ec2.elb.tag.Tag` objects ''' params = {} if load_balancer_names: conn.build_list_params(params, load_balancer_names, 'LoadBalancerNames.member.%d') tags = conn.get_object( 'DescribeTags', params, __utils__['boto_elb_tag.get_tag_descriptions'](), verb='POST' ) if tags[load_balancer_names]: return tags[load_balancer_names] else: return None def _add_tags(conn, load_balancer_names, tags): ''' Create new metadata tags for the specified resource ids. :type load_balancer_names: list :param load_balancer_names: A list of load balancer names. :type tags: dict :param tags: A dictionary containing the name/value pairs. If you want to create only a tag name, the value for that tag should be the empty string (e.g. ''). ''' params = {} conn.build_list_params(params, load_balancer_names, 'LoadBalancerNames.member.%d') _build_tag_param_list(params, tags) return conn.get_status('AddTags', params, verb='POST') def _remove_tags(conn, load_balancer_names, tags): ''' Delete metadata tags for the specified resource ids. :type load_balancer_names: list :param load_balancer_names: A list of load balancer names. :type tags: list :param tags: A list containing just tag names for the tags to be deleted. ''' params = {} conn.build_list_params(params, load_balancer_names, 'LoadBalancerNames.member.%d') conn.build_list_params(params, tags, 'Tags.member.%d.Key') return conn.get_status('RemoveTags', params, verb='POST')
saltstack/salt
salt/modules/boto_elb.py
register_instances
python
def register_instances(name, instances, region=None, key=None, keyid=None, profile=None): ''' Register instances with an ELB. Instances is either a string instance id or a list of string instance id's. Returns: - ``True``: instance(s) registered successfully - ``False``: instance(s) failed to be registered CLI example: .. code-block:: bash salt myminion boto_elb.register_instances myelb instance_id salt myminion boto_elb.register_instances myelb "[instance_id,instance_id]" ''' # convert instances to list type, enabling consistent use of instances # variable throughout the register_instances method if isinstance(instances, six.string_types) or isinstance(instances, six.text_type): instances = [instances] conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: registered_instances = conn.register_instances(name, instances) except boto.exception.BotoServerError as error: log.warning(error) return False registered_instance_ids = [instance.id for instance in registered_instances] # register_failues is a set that will contain any instances that were not # able to be registered with the given ELB register_failures = set(instances).difference(set(registered_instance_ids)) if register_failures: log.warning('Instance(s): %s not registered with ELB %s.', list(register_failures), name) register_result = False else: register_result = True return register_result
Register instances with an ELB. Instances is either a string instance id or a list of string instance id's. Returns: - ``True``: instance(s) registered successfully - ``False``: instance(s) failed to be registered CLI example: .. code-block:: bash salt myminion boto_elb.register_instances myelb instance_id salt myminion boto_elb.register_instances myelb "[instance_id,instance_id]"
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_elb.py#L692-L732
null
# -*- coding: utf-8 -*- ''' Connection module for Amazon ELB .. versionadded:: 2014.7.0 :configuration: This module accepts explicit elb credentials but can also utilize IAM roles assigned to the instance through Instance Profiles. Dynamic credentials are then automatically obtained from AWS API and no further configuration is necessary. More Information available at: .. code-block:: text http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/iam-roles-for-amazon-ec2.html If IAM roles are not used you need to specify them either in a pillar or in the minion's config file: .. code-block:: yaml elb.keyid: GKTADJGHEIQSXMKKRBJ08H elb.key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs A region may also be specified in the configuration: .. code-block:: yaml elb.region: us-east-1 If a region is not specified, the default is us-east-1. It's also possible to specify key, keyid and region via a profile, either as a passed in dict, or as a string to pull from pillars or minion config: .. code-block:: yaml myprofile: keyid: GKTADJGHEIQSXMKKRBJ08H key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs region: us-east-1 :depends: boto >= 2.33.0 ''' # keep lint from choking on _get_conn and _cache_id # pylint: disable=E0602 from __future__ import absolute_import, print_function, unicode_literals # Import Python libs import logging import time log = logging.getLogger(__name__) # Import Salt libs import salt.utils.json import salt.utils.odict as odict import salt.utils.versions # Import third party libs from salt.ext import six try: import boto import boto.ec2 # pylint: enable=unused-import from boto.ec2.elb import HealthCheck from boto.ec2.elb.attributes import AccessLogAttribute from boto.ec2.elb.attributes import ConnectionDrainingAttribute from boto.ec2.elb.attributes import ConnectionSettingAttribute from boto.ec2.elb.attributes import CrossZoneLoadBalancingAttribute logging.getLogger('boto').setLevel(logging.CRITICAL) HAS_BOTO = True except ImportError: HAS_BOTO = False def __virtual__(): ''' Only load if boto libraries exist. ''' # connection settings were added in 2.33.0 has_boto_reqs = salt.utils.versions.check_boto_reqs( boto_ver='2.33.0', check_boto3=False ) if has_boto_reqs is True: __utils__['boto.assign_funcs'](__name__, 'elb', module='ec2.elb', pack=__salt__) return has_boto_reqs def exists(name, region=None, key=None, keyid=None, profile=None): ''' Check to see if an ELB exists. CLI example: .. code-block:: bash salt myminion boto_elb.exists myelb region=us-east-1 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: elb = conn.get_all_load_balancers(load_balancer_names=[name]) if elb: return True else: log.debug('The load balancer does not exist in region %s', region) return False except boto.exception.BotoServerError as error: log.warning(error) return False def get_all_elbs(region=None, key=None, keyid=None, profile=None): ''' Return all load balancers associated with an account CLI example: .. code-block:: bash salt myminion boto_elb.get_all_elbs region=us-east-1 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: return [e for e in conn.get_all_load_balancers()] except boto.exception.BotoServerError as error: log.warning(error) return [] def list_elbs(region=None, key=None, keyid=None, profile=None): ''' Return names of all load balancers associated with an account CLI example: .. code-block:: bash salt myminion boto_elb.list_elbs region=us-east-1 ''' return [e.name for e in get_all_elbs(region=region, key=key, keyid=keyid, profile=profile)] def get_elb_config(name, region=None, key=None, keyid=None, profile=None): ''' Get an ELB configuration. CLI example: .. code-block:: bash salt myminion boto_elb.exists myelb region=us-east-1 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) retries = 30 while retries: try: lb = conn.get_all_load_balancers(load_balancer_names=[name]) lb = lb[0] ret = {} ret['availability_zones'] = lb.availability_zones listeners = [] for _listener in lb.listeners: listener_dict = {} listener_dict['elb_port'] = _listener.load_balancer_port listener_dict['elb_protocol'] = _listener.protocol listener_dict['instance_port'] = _listener.instance_port listener_dict['instance_protocol'] = _listener.instance_protocol listener_dict['policies'] = _listener.policy_names if _listener.ssl_certificate_id: listener_dict['certificate'] = _listener.ssl_certificate_id listeners.append(listener_dict) ret['listeners'] = listeners backends = [] for _backend in lb.backends: bs_dict = {} bs_dict['instance_port'] = _backend.instance_port bs_dict['policies'] = [p.policy_name for p in _backend.policies] backends.append(bs_dict) ret['backends'] = backends ret['subnets'] = lb.subnets ret['security_groups'] = lb.security_groups ret['scheme'] = lb.scheme ret['dns_name'] = lb.dns_name ret['tags'] = _get_all_tags(conn, name) lb_policy_lists = [ lb.policies.app_cookie_stickiness_policies, lb.policies.lb_cookie_stickiness_policies, lb.policies.other_policies ] policies = [] for policy_list in lb_policy_lists: policies += [p.policy_name for p in policy_list] ret['policies'] = policies return ret except boto.exception.BotoServerError as error: if error.error_code == 'Throttling': log.debug('Throttled by AWS API, will retry in 5 seconds.') time.sleep(5) retries -= 1 continue log.error('Error fetching config for ELB %s: %s', name, error.message) log.error(error) return {} return {} def listener_dict_to_tuple(listener): ''' Convert an ELB listener dict into a listener tuple used by certain parts of the AWS ELB API. CLI example: .. code-block:: bash salt myminion boto_elb.listener_dict_to_tuple '{"elb_port":80,"instance_port":80,"elb_protocol":"HTTP"}' ''' # We define all listeners as complex listeners. if 'instance_protocol' not in listener: instance_protocol = listener['elb_protocol'].upper() else: instance_protocol = listener['instance_protocol'].upper() listener_tuple = [listener['elb_port'], listener['instance_port'], listener['elb_protocol'], instance_protocol] if 'certificate' in listener: listener_tuple.append(listener['certificate']) return tuple(listener_tuple) def create(name, availability_zones, listeners, subnets=None, security_groups=None, scheme='internet-facing', region=None, key=None, keyid=None, profile=None): ''' Create an ELB CLI example to create an ELB: .. code-block:: bash salt myminion boto_elb.create myelb '["us-east-1a", "us-east-1e"]' '{"elb_port": 443, "elb_protocol": "HTTPS", ...}' region=us-east-1 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if exists(name, region, key, keyid, profile): return True if isinstance(availability_zones, six.string_types): availability_zones = salt.utils.json.loads(availability_zones) if isinstance(listeners, six.string_types): listeners = salt.utils.json.loads(listeners) _complex_listeners = [] for listener in listeners: _complex_listeners.append(listener_dict_to_tuple(listener)) try: lb = conn.create_load_balancer(name=name, zones=availability_zones, subnets=subnets, security_groups=security_groups, scheme=scheme, complex_listeners=_complex_listeners) if lb: log.info('Created ELB %s', name) return True else: log.error('Failed to create ELB %s', name) return False except boto.exception.BotoServerError as error: log.error('Failed to create ELB %s: %s: %s', name, error.error_code, error.message, exc_info_on_loglevel=logging.DEBUG) return False def delete(name, region=None, key=None, keyid=None, profile=None): ''' Delete an ELB. CLI example to delete an ELB: .. code-block:: bash salt myminion boto_elb.delete myelb region=us-east-1 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not exists(name, region, key, keyid, profile): return True try: conn.delete_load_balancer(name) log.info('Deleted ELB %s.', name) return True except boto.exception.BotoServerError as error: log.error('Failed to delete ELB %s', name, exc_info_on_loglevel=logging.DEBUG) return False def create_listeners(name, listeners, region=None, key=None, keyid=None, profile=None): ''' Create listeners on an ELB. CLI example: .. code-block:: bash salt myminion boto_elb.create_listeners myelb '[["HTTPS", "HTTP", 443, 80, "arn:aws:iam::11 11111:server-certificate/mycert"]]' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if isinstance(listeners, six.string_types): listeners = salt.utils.json.loads(listeners) _complex_listeners = [] for listener in listeners: _complex_listeners.append(listener_dict_to_tuple(listener)) try: conn.create_load_balancer_listeners(name, [], _complex_listeners) log.info('Created ELB listeners on %s', name) return True except boto.exception.BotoServerError as error: log.error('Failed to create ELB listeners on %s: %s', name, error, exc_info_on_loglevel=logging.DEBUG) return False def delete_listeners(name, ports, region=None, key=None, keyid=None, profile=None): ''' Delete listeners on an ELB. CLI example: .. code-block:: bash salt myminion boto_elb.delete_listeners myelb '[80,443]' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if isinstance(ports, six.string_types): ports = salt.utils.json.loads(ports) try: conn.delete_load_balancer_listeners(name, ports) log.info('Deleted ELB listeners on %s', name) return True except boto.exception.BotoServerError as error: log.error('Failed to delete ELB listeners on %s: %s', name, error, exc_info_on_loglevel=logging.DEBUG) return False def apply_security_groups(name, security_groups, region=None, key=None, keyid=None, profile=None): ''' Apply security groups to ELB. CLI example: .. code-block:: bash salt myminion boto_elb.apply_security_groups myelb '["mysecgroup1"]' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if isinstance(security_groups, six.string_types): security_groups = salt.utils.json.loads(security_groups) try: conn.apply_security_groups_to_lb(name, security_groups) log.info('Applied security_groups on ELB %s', name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to appply security_groups on ELB %s: %s', name, e.message) return False def enable_availability_zones(name, availability_zones, region=None, key=None, keyid=None, profile=None): ''' Enable availability zones for ELB. CLI example: .. code-block:: bash salt myminion boto_elb.enable_availability_zones myelb '["us-east-1a"]' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if isinstance(availability_zones, six.string_types): availability_zones = salt.utils.json.loads(availability_zones) try: conn.enable_availability_zones(name, availability_zones) log.info('Enabled availability_zones on ELB %s', name) return True except boto.exception.BotoServerError as error: log.error('Failed to enable availability_zones on ELB %s: %s', name, error) return False def disable_availability_zones(name, availability_zones, region=None, key=None, keyid=None, profile=None): ''' Disable availability zones for ELB. CLI example: .. code-block:: bash salt myminion boto_elb.disable_availability_zones myelb '["us-east-1a"]' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if isinstance(availability_zones, six.string_types): availability_zones = salt.utils.json.loads(availability_zones) try: conn.disable_availability_zones(name, availability_zones) log.info('Disabled availability_zones on ELB %s', name) return True except boto.exception.BotoServerError as error: log.error('Failed to disable availability_zones on ELB %s: %s', name, error, exc_info_on_loglevel=logging.DEBUG) return False def attach_subnets(name, subnets, region=None, key=None, keyid=None, profile=None): ''' Attach ELB to subnets. CLI example: .. code-block:: bash salt myminion boto_elb.attach_subnets myelb '["mysubnet"]' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if isinstance(subnets, six.string_types): subnets = salt.utils.json.loads(subnets) try: conn.attach_lb_to_subnets(name, subnets) log.info('Attached ELB %s on subnets.', name) return True except boto.exception.BotoServerError as error: log.error('Failed to attach ELB %s on subnets: %s', name, error, exc_info_on_loglevel=logging.DEBUG) return False def detach_subnets(name, subnets, region=None, key=None, keyid=None, profile=None): ''' Detach ELB from subnets. CLI example: .. code-block:: bash salt myminion boto_elb.detach_subnets myelb '["mysubnet"]' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if isinstance(subnets, six.string_types): subnets = salt.utils.json.loads(subnets) try: conn.detach_lb_from_subnets(name, subnets) log.info('Detached ELB %s from subnets.', name) return True except boto.exception.BotoServerError as error: log.error('Failed to detach ELB %s from subnets: %s', name, error, exc_info_on_loglevel=logging.DEBUG) return False def get_attributes(name, region=None, key=None, keyid=None, profile=None): ''' Check to see if attributes are set on an ELB. CLI example: .. code-block:: bash salt myminion boto_elb.get_attributes myelb ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) retries = 30 while retries: try: lbattrs = conn.get_all_lb_attributes(name) ret = odict.OrderedDict() ret['access_log'] = odict.OrderedDict() ret['cross_zone_load_balancing'] = odict.OrderedDict() ret['connection_draining'] = odict.OrderedDict() ret['connecting_settings'] = odict.OrderedDict() al = lbattrs.access_log czlb = lbattrs.cross_zone_load_balancing cd = lbattrs.connection_draining cs = lbattrs.connecting_settings ret['access_log']['enabled'] = al.enabled ret['access_log']['s3_bucket_name'] = al.s3_bucket_name ret['access_log']['s3_bucket_prefix'] = al.s3_bucket_prefix ret['access_log']['emit_interval'] = al.emit_interval ret['cross_zone_load_balancing']['enabled'] = czlb.enabled ret['connection_draining']['enabled'] = cd.enabled ret['connection_draining']['timeout'] = cd.timeout ret['connecting_settings']['idle_timeout'] = cs.idle_timeout return ret except boto.exception.BotoServerError as e: if e.error_code == 'Throttling': log.debug("Throttled by AWS API, will retry in 5 seconds...") time.sleep(5) retries -= 1 continue log.error('ELB %s does not exist: %s', name, e.message) return {} return {} def set_attributes(name, attributes, region=None, key=None, keyid=None, profile=None): ''' Set attributes on an ELB. name (string) Name of the ELB instance to set attributes for attributes A dict of attributes to set. Valid attributes are: access_log (dict) enabled (bool) Enable storage of access logs. s3_bucket_name (string) The name of the S3 bucket to place logs. s3_bucket_prefix (string) Prefix for the log file name. emit_interval (int) Interval for storing logs in S3 in minutes. Valid values are 5 and 60. connection_draining (dict) enabled (bool) Enable connection draining. timeout (int) Maximum allowed time in seconds for sending existing connections to an instance that is deregistering or unhealthy. Default is 300. cross_zone_load_balancing (dict) enabled (bool) Enable cross-zone load balancing. CLI example to set attributes on an ELB: .. code-block:: bash salt myminion boto_elb.set_attributes myelb '{"access_log": {"enabled": "true", "s3_bucket_name": "mybucket", "s3_bucket_prefix": "mylogs/", "emit_interval": "5"}}' region=us-east-1 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) al = attributes.get('access_log', {}) czlb = attributes.get('cross_zone_load_balancing', {}) cd = attributes.get('connection_draining', {}) cs = attributes.get('connecting_settings', {}) if not al and not czlb and not cd and not cs: log.error('No supported attributes for ELB.') return False if al: _al = AccessLogAttribute() _al.enabled = al.get('enabled', False) if not _al.enabled: msg = 'Access log attribute configured, but enabled config missing' log.error(msg) return False _al.s3_bucket_name = al.get('s3_bucket_name', None) _al.s3_bucket_prefix = al.get('s3_bucket_prefix', None) _al.emit_interval = al.get('emit_interval', None) added_attr = conn.modify_lb_attribute(name, 'accessLog', _al) if added_attr: log.info('Added access_log attribute to %s elb.', name) else: log.error('Failed to add access_log attribute to %s elb.', name) return False if czlb: _czlb = CrossZoneLoadBalancingAttribute() _czlb.enabled = czlb['enabled'] added_attr = conn.modify_lb_attribute(name, 'crossZoneLoadBalancing', _czlb.enabled) if added_attr: log.info('Added cross_zone_load_balancing attribute to %s elb.', name) else: log.error('Failed to add cross_zone_load_balancing attribute.') return False if cd: _cd = ConnectionDrainingAttribute() _cd.enabled = cd['enabled'] _cd.timeout = cd.get('timeout', 300) added_attr = conn.modify_lb_attribute(name, 'connectionDraining', _cd) if added_attr: log.info('Added connection_draining attribute to %s elb.', name) else: log.error('Failed to add connection_draining attribute.') return False if cs: _cs = ConnectionSettingAttribute() _cs.idle_timeout = cs.get('idle_timeout', 60) added_attr = conn.modify_lb_attribute(name, 'connectingSettings', _cs) if added_attr: log.info('Added connecting_settings attribute to %s elb.', name) else: log.error('Failed to add connecting_settings attribute.') return False return True def get_health_check(name, region=None, key=None, keyid=None, profile=None): ''' Get the health check configured for this ELB. CLI example: .. code-block:: bash salt myminion boto_elb.get_health_check myelb ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) retries = 30 while True: try: lb = conn.get_all_load_balancers(load_balancer_names=[name]) lb = lb[0] ret = odict.OrderedDict() hc = lb.health_check ret['interval'] = hc.interval ret['target'] = hc.target ret['healthy_threshold'] = hc.healthy_threshold ret['timeout'] = hc.timeout ret['unhealthy_threshold'] = hc.unhealthy_threshold return ret except boto.exception.BotoServerError as e: if retries and e.code == 'Throttling': log.debug('Throttled by AWS API, will retry in 5 seconds.') time.sleep(5) retries -= 1 continue log.error('ELB %s not found.', name, exc_info_on_logleve=logging.DEBUG) return {} def set_health_check(name, health_check, region=None, key=None, keyid=None, profile=None): ''' Set attributes on an ELB. CLI example to set attributes on an ELB: .. code-block:: bash salt myminion boto_elb.set_health_check myelb '{"target": "HTTP:80/"}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) retries = 30 hc = HealthCheck(**health_check) while True: try: conn.configure_health_check(name, hc) log.info('Configured health check on ELB %s', name) return True except boto.exception.BotoServerError as error: if retries and e.code == 'Throttling': log.debug('Throttled by AWS API, will retry in 5 seconds.') time.sleep(5) retries -= 1 continue log.exception('Failed to configure health check on ELB %s', name) return False def deregister_instances(name, instances, region=None, key=None, keyid=None, profile=None): ''' Deregister instances with an ELB. Instances is either a string instance id or a list of string instance id's. Returns: - ``True``: instance(s) deregistered successfully - ``False``: instance(s) failed to be deregistered - ``None``: instance(s) not valid or not registered, no action taken CLI example: .. code-block:: bash salt myminion boto_elb.deregister_instances myelb instance_id salt myminion boto_elb.deregister_instances myelb "[instance_id, instance_id]" ''' # convert instances to list type, enabling consistent use of instances # variable throughout the deregister_instances method if isinstance(instances, six.string_types) or isinstance(instances, six.text_type): instances = [instances] conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: registered_instances = conn.deregister_instances(name, instances) except boto.exception.BotoServerError as error: # if the instance(s) given as an argument are not members of the ELB # boto returns error.error_code == 'InvalidInstance' # deregister_instances returns "None" because the instances are # effectively deregistered from ELB if error.error_code == 'InvalidInstance': log.warning( 'One or more of instance(s) %s are not part of ELB %s. ' 'deregister_instances not performed.', instances, name ) return None else: log.warning(error) return False registered_instance_ids = [instance.id for instance in registered_instances] # deregister_failures is a set that will contain any instances that were # unable to be deregistered from the given ELB deregister_failures = set(instances).intersection(set(registered_instance_ids)) if deregister_failures: log.warning( 'Instance(s): %s not deregistered from ELB %s.', list(deregister_failures), name ) deregister_result = False else: deregister_result = True return deregister_result def set_instances(name, instances, test=False, region=None, key=None, keyid=None, profile=None): ''' Set the instances assigned to an ELB to exactly the list given CLI example: .. code-block:: bash salt myminion boto_elb.set_instances myelb region=us-east-1 instances="[instance_id,instance_id]" ''' ret = True current = set([i['instance_id'] for i in get_instance_health(name, region, key, keyid, profile)]) desired = set(instances) add = desired - current remove = current - desired if test: return bool(add or remove) if remove: if deregister_instances(name, list(remove), region, key, keyid, profile) is False: ret = False if add: if register_instances(name, list(add), region, key, keyid, profile) is False: ret = False return ret def get_instance_health(name, region=None, key=None, keyid=None, profile=None, instances=None): ''' Get a list of instances and their health state CLI example: .. code-block:: bash salt myminion boto_elb.get_instance_health myelb salt myminion boto_elb.get_instance_health myelb region=us-east-1 instances="[instance_id,instance_id]" ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: instance_states = conn.describe_instance_health(name, instances) ret = [] for _instance in instance_states: ret.append({'instance_id': _instance.instance_id, 'description': _instance.description, 'state': _instance.state, 'reason_code': _instance.reason_code }) return ret except boto.exception.BotoServerError as error: log.debug(error) return [] def create_policy(name, policy_name, policy_type, policy, region=None, key=None, keyid=None, profile=None): ''' Create an ELB policy. .. versionadded:: 2016.3.0 CLI example: .. code-block:: bash salt myminion boto_elb.create_policy myelb mypolicy LBCookieStickinessPolicyType '{"CookieExpirationPeriod": 3600}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not exists(name, region, key, keyid, profile): return False try: success = conn.create_lb_policy(name, policy_name, policy_type, policy) if success: log.info('Created policy %s on ELB %s', policy_name, name) return True else: log.error('Failed to create policy %s on ELB %s', policy_name, name) return False except boto.exception.BotoServerError as e: log.error('Failed to create policy %s on ELB %s: %s', policy_name, name, e.message, exc_info_on_loglevel=logging.DEBUG) return False def delete_policy(name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Delete an ELB policy. .. versionadded:: 2016.3.0 CLI example: .. code-block:: bash salt myminion boto_elb.delete_policy myelb mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not exists(name, region, key, keyid, profile): return True try: conn.delete_lb_policy(name, policy_name) log.info('Deleted policy %s on ELB %s', policy_name, name) return True except boto.exception.BotoServerError as e: log.error('Failed to delete policy %s on ELB %s: %s', policy_name, name, e.message, exc_info_on_loglevel=logging.DEBUG) return False def set_listener_policy(name, port, policies=None, region=None, key=None, keyid=None, profile=None): ''' Set the policies of an ELB listener. .. versionadded:: 2016.3.0 CLI example: .. code-block:: Bash salt myminion boto_elb.set_listener_policy myelb 443 "[policy1,policy2]" ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not exists(name, region, key, keyid, profile): return True if policies is None: policies = [] try: conn.set_lb_policies_of_listener(name, port, policies) log.info('Set policies %s on ELB %s listener %s', policies, name, port) except boto.exception.BotoServerError as e: log.info('Failed to set policy %s on ELB %s listener %s: %s', policies, name, port, e.message, exc_info_on_loglevel=logging.DEBUG) return False return True def set_backend_policy(name, port, policies=None, region=None, key=None, keyid=None, profile=None): ''' Set the policies of an ELB backend server. CLI example: salt myminion boto_elb.set_backend_policy myelb 443 "[policy1,policy2]" ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not exists(name, region, key, keyid, profile): return True if policies is None: policies = [] try: conn.set_lb_policies_of_backend_server(name, port, policies) log.info('Set policies %s on ELB %s backend server %s', policies, name, port) except boto.exception.BotoServerError as e: log.info('Failed to set policy %s on ELB %s backend server %s: %s', policies, name, port, e.message, exc_info_on_loglevel=logging.DEBUG) return False return True def set_tags(name, tags, region=None, key=None, keyid=None, profile=None): ''' Add the tags on an ELB .. versionadded:: 2016.3.0 name name of the ELB tags dict of name/value pair tags CLI Example: .. code-block:: bash salt myminion boto_elb.set_tags my-elb-name "{'Tag1': 'Value', 'Tag2': 'Another Value'}" ''' if exists(name, region, key, keyid, profile): conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) ret = _add_tags(conn, name, tags) return ret else: return False def delete_tags(name, tags, region=None, key=None, keyid=None, profile=None): ''' Add the tags on an ELB name name of the ELB tags list of tags to remove CLI Example: .. code-block:: bash salt myminion boto_elb.delete_tags my-elb-name ['TagToRemove1', 'TagToRemove2'] ''' if exists(name, region, key, keyid, profile): conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) ret = _remove_tags(conn, name, tags) return ret else: return False def _build_tag_param_list(params, tags): ''' helper function to build a tag parameter list to send ''' keys = sorted(tags.keys()) i = 1 for key in keys: value = tags[key] params['Tags.member.{0}.Key'.format(i)] = key if value is not None: params['Tags.member.{0}.Value'.format(i)] = value i += 1 def _get_all_tags(conn, load_balancer_names=None): ''' Retrieve all the metadata tags associated with your ELB(s). :type load_balancer_names: list :param load_balancer_names: An optional list of load balancer names. :rtype: list :return: A list of :class:`boto.ec2.elb.tag.Tag` objects ''' params = {} if load_balancer_names: conn.build_list_params(params, load_balancer_names, 'LoadBalancerNames.member.%d') tags = conn.get_object( 'DescribeTags', params, __utils__['boto_elb_tag.get_tag_descriptions'](), verb='POST' ) if tags[load_balancer_names]: return tags[load_balancer_names] else: return None def _add_tags(conn, load_balancer_names, tags): ''' Create new metadata tags for the specified resource ids. :type load_balancer_names: list :param load_balancer_names: A list of load balancer names. :type tags: dict :param tags: A dictionary containing the name/value pairs. If you want to create only a tag name, the value for that tag should be the empty string (e.g. ''). ''' params = {} conn.build_list_params(params, load_balancer_names, 'LoadBalancerNames.member.%d') _build_tag_param_list(params, tags) return conn.get_status('AddTags', params, verb='POST') def _remove_tags(conn, load_balancer_names, tags): ''' Delete metadata tags for the specified resource ids. :type load_balancer_names: list :param load_balancer_names: A list of load balancer names. :type tags: list :param tags: A list containing just tag names for the tags to be deleted. ''' params = {} conn.build_list_params(params, load_balancer_names, 'LoadBalancerNames.member.%d') conn.build_list_params(params, tags, 'Tags.member.%d.Key') return conn.get_status('RemoveTags', params, verb='POST')
saltstack/salt
salt/modules/boto_elb.py
deregister_instances
python
def deregister_instances(name, instances, region=None, key=None, keyid=None, profile=None): ''' Deregister instances with an ELB. Instances is either a string instance id or a list of string instance id's. Returns: - ``True``: instance(s) deregistered successfully - ``False``: instance(s) failed to be deregistered - ``None``: instance(s) not valid or not registered, no action taken CLI example: .. code-block:: bash salt myminion boto_elb.deregister_instances myelb instance_id salt myminion boto_elb.deregister_instances myelb "[instance_id, instance_id]" ''' # convert instances to list type, enabling consistent use of instances # variable throughout the deregister_instances method if isinstance(instances, six.string_types) or isinstance(instances, six.text_type): instances = [instances] conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: registered_instances = conn.deregister_instances(name, instances) except boto.exception.BotoServerError as error: # if the instance(s) given as an argument are not members of the ELB # boto returns error.error_code == 'InvalidInstance' # deregister_instances returns "None" because the instances are # effectively deregistered from ELB if error.error_code == 'InvalidInstance': log.warning( 'One or more of instance(s) %s are not part of ELB %s. ' 'deregister_instances not performed.', instances, name ) return None else: log.warning(error) return False registered_instance_ids = [instance.id for instance in registered_instances] # deregister_failures is a set that will contain any instances that were # unable to be deregistered from the given ELB deregister_failures = set(instances).intersection(set(registered_instance_ids)) if deregister_failures: log.warning( 'Instance(s): %s not deregistered from ELB %s.', list(deregister_failures), name ) deregister_result = False else: deregister_result = True return deregister_result
Deregister instances with an ELB. Instances is either a string instance id or a list of string instance id's. Returns: - ``True``: instance(s) deregistered successfully - ``False``: instance(s) failed to be deregistered - ``None``: instance(s) not valid or not registered, no action taken CLI example: .. code-block:: bash salt myminion boto_elb.deregister_instances myelb instance_id salt myminion boto_elb.deregister_instances myelb "[instance_id, instance_id]"
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_elb.py#L735-L789
null
# -*- coding: utf-8 -*- ''' Connection module for Amazon ELB .. versionadded:: 2014.7.0 :configuration: This module accepts explicit elb credentials but can also utilize IAM roles assigned to the instance through Instance Profiles. Dynamic credentials are then automatically obtained from AWS API and no further configuration is necessary. More Information available at: .. code-block:: text http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/iam-roles-for-amazon-ec2.html If IAM roles are not used you need to specify them either in a pillar or in the minion's config file: .. code-block:: yaml elb.keyid: GKTADJGHEIQSXMKKRBJ08H elb.key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs A region may also be specified in the configuration: .. code-block:: yaml elb.region: us-east-1 If a region is not specified, the default is us-east-1. It's also possible to specify key, keyid and region via a profile, either as a passed in dict, or as a string to pull from pillars or minion config: .. code-block:: yaml myprofile: keyid: GKTADJGHEIQSXMKKRBJ08H key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs region: us-east-1 :depends: boto >= 2.33.0 ''' # keep lint from choking on _get_conn and _cache_id # pylint: disable=E0602 from __future__ import absolute_import, print_function, unicode_literals # Import Python libs import logging import time log = logging.getLogger(__name__) # Import Salt libs import salt.utils.json import salt.utils.odict as odict import salt.utils.versions # Import third party libs from salt.ext import six try: import boto import boto.ec2 # pylint: enable=unused-import from boto.ec2.elb import HealthCheck from boto.ec2.elb.attributes import AccessLogAttribute from boto.ec2.elb.attributes import ConnectionDrainingAttribute from boto.ec2.elb.attributes import ConnectionSettingAttribute from boto.ec2.elb.attributes import CrossZoneLoadBalancingAttribute logging.getLogger('boto').setLevel(logging.CRITICAL) HAS_BOTO = True except ImportError: HAS_BOTO = False def __virtual__(): ''' Only load if boto libraries exist. ''' # connection settings were added in 2.33.0 has_boto_reqs = salt.utils.versions.check_boto_reqs( boto_ver='2.33.0', check_boto3=False ) if has_boto_reqs is True: __utils__['boto.assign_funcs'](__name__, 'elb', module='ec2.elb', pack=__salt__) return has_boto_reqs def exists(name, region=None, key=None, keyid=None, profile=None): ''' Check to see if an ELB exists. CLI example: .. code-block:: bash salt myminion boto_elb.exists myelb region=us-east-1 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: elb = conn.get_all_load_balancers(load_balancer_names=[name]) if elb: return True else: log.debug('The load balancer does not exist in region %s', region) return False except boto.exception.BotoServerError as error: log.warning(error) return False def get_all_elbs(region=None, key=None, keyid=None, profile=None): ''' Return all load balancers associated with an account CLI example: .. code-block:: bash salt myminion boto_elb.get_all_elbs region=us-east-1 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: return [e for e in conn.get_all_load_balancers()] except boto.exception.BotoServerError as error: log.warning(error) return [] def list_elbs(region=None, key=None, keyid=None, profile=None): ''' Return names of all load balancers associated with an account CLI example: .. code-block:: bash salt myminion boto_elb.list_elbs region=us-east-1 ''' return [e.name for e in get_all_elbs(region=region, key=key, keyid=keyid, profile=profile)] def get_elb_config(name, region=None, key=None, keyid=None, profile=None): ''' Get an ELB configuration. CLI example: .. code-block:: bash salt myminion boto_elb.exists myelb region=us-east-1 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) retries = 30 while retries: try: lb = conn.get_all_load_balancers(load_balancer_names=[name]) lb = lb[0] ret = {} ret['availability_zones'] = lb.availability_zones listeners = [] for _listener in lb.listeners: listener_dict = {} listener_dict['elb_port'] = _listener.load_balancer_port listener_dict['elb_protocol'] = _listener.protocol listener_dict['instance_port'] = _listener.instance_port listener_dict['instance_protocol'] = _listener.instance_protocol listener_dict['policies'] = _listener.policy_names if _listener.ssl_certificate_id: listener_dict['certificate'] = _listener.ssl_certificate_id listeners.append(listener_dict) ret['listeners'] = listeners backends = [] for _backend in lb.backends: bs_dict = {} bs_dict['instance_port'] = _backend.instance_port bs_dict['policies'] = [p.policy_name for p in _backend.policies] backends.append(bs_dict) ret['backends'] = backends ret['subnets'] = lb.subnets ret['security_groups'] = lb.security_groups ret['scheme'] = lb.scheme ret['dns_name'] = lb.dns_name ret['tags'] = _get_all_tags(conn, name) lb_policy_lists = [ lb.policies.app_cookie_stickiness_policies, lb.policies.lb_cookie_stickiness_policies, lb.policies.other_policies ] policies = [] for policy_list in lb_policy_lists: policies += [p.policy_name for p in policy_list] ret['policies'] = policies return ret except boto.exception.BotoServerError as error: if error.error_code == 'Throttling': log.debug('Throttled by AWS API, will retry in 5 seconds.') time.sleep(5) retries -= 1 continue log.error('Error fetching config for ELB %s: %s', name, error.message) log.error(error) return {} return {} def listener_dict_to_tuple(listener): ''' Convert an ELB listener dict into a listener tuple used by certain parts of the AWS ELB API. CLI example: .. code-block:: bash salt myminion boto_elb.listener_dict_to_tuple '{"elb_port":80,"instance_port":80,"elb_protocol":"HTTP"}' ''' # We define all listeners as complex listeners. if 'instance_protocol' not in listener: instance_protocol = listener['elb_protocol'].upper() else: instance_protocol = listener['instance_protocol'].upper() listener_tuple = [listener['elb_port'], listener['instance_port'], listener['elb_protocol'], instance_protocol] if 'certificate' in listener: listener_tuple.append(listener['certificate']) return tuple(listener_tuple) def create(name, availability_zones, listeners, subnets=None, security_groups=None, scheme='internet-facing', region=None, key=None, keyid=None, profile=None): ''' Create an ELB CLI example to create an ELB: .. code-block:: bash salt myminion boto_elb.create myelb '["us-east-1a", "us-east-1e"]' '{"elb_port": 443, "elb_protocol": "HTTPS", ...}' region=us-east-1 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if exists(name, region, key, keyid, profile): return True if isinstance(availability_zones, six.string_types): availability_zones = salt.utils.json.loads(availability_zones) if isinstance(listeners, six.string_types): listeners = salt.utils.json.loads(listeners) _complex_listeners = [] for listener in listeners: _complex_listeners.append(listener_dict_to_tuple(listener)) try: lb = conn.create_load_balancer(name=name, zones=availability_zones, subnets=subnets, security_groups=security_groups, scheme=scheme, complex_listeners=_complex_listeners) if lb: log.info('Created ELB %s', name) return True else: log.error('Failed to create ELB %s', name) return False except boto.exception.BotoServerError as error: log.error('Failed to create ELB %s: %s: %s', name, error.error_code, error.message, exc_info_on_loglevel=logging.DEBUG) return False def delete(name, region=None, key=None, keyid=None, profile=None): ''' Delete an ELB. CLI example to delete an ELB: .. code-block:: bash salt myminion boto_elb.delete myelb region=us-east-1 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not exists(name, region, key, keyid, profile): return True try: conn.delete_load_balancer(name) log.info('Deleted ELB %s.', name) return True except boto.exception.BotoServerError as error: log.error('Failed to delete ELB %s', name, exc_info_on_loglevel=logging.DEBUG) return False def create_listeners(name, listeners, region=None, key=None, keyid=None, profile=None): ''' Create listeners on an ELB. CLI example: .. code-block:: bash salt myminion boto_elb.create_listeners myelb '[["HTTPS", "HTTP", 443, 80, "arn:aws:iam::11 11111:server-certificate/mycert"]]' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if isinstance(listeners, six.string_types): listeners = salt.utils.json.loads(listeners) _complex_listeners = [] for listener in listeners: _complex_listeners.append(listener_dict_to_tuple(listener)) try: conn.create_load_balancer_listeners(name, [], _complex_listeners) log.info('Created ELB listeners on %s', name) return True except boto.exception.BotoServerError as error: log.error('Failed to create ELB listeners on %s: %s', name, error, exc_info_on_loglevel=logging.DEBUG) return False def delete_listeners(name, ports, region=None, key=None, keyid=None, profile=None): ''' Delete listeners on an ELB. CLI example: .. code-block:: bash salt myminion boto_elb.delete_listeners myelb '[80,443]' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if isinstance(ports, six.string_types): ports = salt.utils.json.loads(ports) try: conn.delete_load_balancer_listeners(name, ports) log.info('Deleted ELB listeners on %s', name) return True except boto.exception.BotoServerError as error: log.error('Failed to delete ELB listeners on %s: %s', name, error, exc_info_on_loglevel=logging.DEBUG) return False def apply_security_groups(name, security_groups, region=None, key=None, keyid=None, profile=None): ''' Apply security groups to ELB. CLI example: .. code-block:: bash salt myminion boto_elb.apply_security_groups myelb '["mysecgroup1"]' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if isinstance(security_groups, six.string_types): security_groups = salt.utils.json.loads(security_groups) try: conn.apply_security_groups_to_lb(name, security_groups) log.info('Applied security_groups on ELB %s', name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to appply security_groups on ELB %s: %s', name, e.message) return False def enable_availability_zones(name, availability_zones, region=None, key=None, keyid=None, profile=None): ''' Enable availability zones for ELB. CLI example: .. code-block:: bash salt myminion boto_elb.enable_availability_zones myelb '["us-east-1a"]' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if isinstance(availability_zones, six.string_types): availability_zones = salt.utils.json.loads(availability_zones) try: conn.enable_availability_zones(name, availability_zones) log.info('Enabled availability_zones on ELB %s', name) return True except boto.exception.BotoServerError as error: log.error('Failed to enable availability_zones on ELB %s: %s', name, error) return False def disable_availability_zones(name, availability_zones, region=None, key=None, keyid=None, profile=None): ''' Disable availability zones for ELB. CLI example: .. code-block:: bash salt myminion boto_elb.disable_availability_zones myelb '["us-east-1a"]' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if isinstance(availability_zones, six.string_types): availability_zones = salt.utils.json.loads(availability_zones) try: conn.disable_availability_zones(name, availability_zones) log.info('Disabled availability_zones on ELB %s', name) return True except boto.exception.BotoServerError as error: log.error('Failed to disable availability_zones on ELB %s: %s', name, error, exc_info_on_loglevel=logging.DEBUG) return False def attach_subnets(name, subnets, region=None, key=None, keyid=None, profile=None): ''' Attach ELB to subnets. CLI example: .. code-block:: bash salt myminion boto_elb.attach_subnets myelb '["mysubnet"]' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if isinstance(subnets, six.string_types): subnets = salt.utils.json.loads(subnets) try: conn.attach_lb_to_subnets(name, subnets) log.info('Attached ELB %s on subnets.', name) return True except boto.exception.BotoServerError as error: log.error('Failed to attach ELB %s on subnets: %s', name, error, exc_info_on_loglevel=logging.DEBUG) return False def detach_subnets(name, subnets, region=None, key=None, keyid=None, profile=None): ''' Detach ELB from subnets. CLI example: .. code-block:: bash salt myminion boto_elb.detach_subnets myelb '["mysubnet"]' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if isinstance(subnets, six.string_types): subnets = salt.utils.json.loads(subnets) try: conn.detach_lb_from_subnets(name, subnets) log.info('Detached ELB %s from subnets.', name) return True except boto.exception.BotoServerError as error: log.error('Failed to detach ELB %s from subnets: %s', name, error, exc_info_on_loglevel=logging.DEBUG) return False def get_attributes(name, region=None, key=None, keyid=None, profile=None): ''' Check to see if attributes are set on an ELB. CLI example: .. code-block:: bash salt myminion boto_elb.get_attributes myelb ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) retries = 30 while retries: try: lbattrs = conn.get_all_lb_attributes(name) ret = odict.OrderedDict() ret['access_log'] = odict.OrderedDict() ret['cross_zone_load_balancing'] = odict.OrderedDict() ret['connection_draining'] = odict.OrderedDict() ret['connecting_settings'] = odict.OrderedDict() al = lbattrs.access_log czlb = lbattrs.cross_zone_load_balancing cd = lbattrs.connection_draining cs = lbattrs.connecting_settings ret['access_log']['enabled'] = al.enabled ret['access_log']['s3_bucket_name'] = al.s3_bucket_name ret['access_log']['s3_bucket_prefix'] = al.s3_bucket_prefix ret['access_log']['emit_interval'] = al.emit_interval ret['cross_zone_load_balancing']['enabled'] = czlb.enabled ret['connection_draining']['enabled'] = cd.enabled ret['connection_draining']['timeout'] = cd.timeout ret['connecting_settings']['idle_timeout'] = cs.idle_timeout return ret except boto.exception.BotoServerError as e: if e.error_code == 'Throttling': log.debug("Throttled by AWS API, will retry in 5 seconds...") time.sleep(5) retries -= 1 continue log.error('ELB %s does not exist: %s', name, e.message) return {} return {} def set_attributes(name, attributes, region=None, key=None, keyid=None, profile=None): ''' Set attributes on an ELB. name (string) Name of the ELB instance to set attributes for attributes A dict of attributes to set. Valid attributes are: access_log (dict) enabled (bool) Enable storage of access logs. s3_bucket_name (string) The name of the S3 bucket to place logs. s3_bucket_prefix (string) Prefix for the log file name. emit_interval (int) Interval for storing logs in S3 in minutes. Valid values are 5 and 60. connection_draining (dict) enabled (bool) Enable connection draining. timeout (int) Maximum allowed time in seconds for sending existing connections to an instance that is deregistering or unhealthy. Default is 300. cross_zone_load_balancing (dict) enabled (bool) Enable cross-zone load balancing. CLI example to set attributes on an ELB: .. code-block:: bash salt myminion boto_elb.set_attributes myelb '{"access_log": {"enabled": "true", "s3_bucket_name": "mybucket", "s3_bucket_prefix": "mylogs/", "emit_interval": "5"}}' region=us-east-1 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) al = attributes.get('access_log', {}) czlb = attributes.get('cross_zone_load_balancing', {}) cd = attributes.get('connection_draining', {}) cs = attributes.get('connecting_settings', {}) if not al and not czlb and not cd and not cs: log.error('No supported attributes for ELB.') return False if al: _al = AccessLogAttribute() _al.enabled = al.get('enabled', False) if not _al.enabled: msg = 'Access log attribute configured, but enabled config missing' log.error(msg) return False _al.s3_bucket_name = al.get('s3_bucket_name', None) _al.s3_bucket_prefix = al.get('s3_bucket_prefix', None) _al.emit_interval = al.get('emit_interval', None) added_attr = conn.modify_lb_attribute(name, 'accessLog', _al) if added_attr: log.info('Added access_log attribute to %s elb.', name) else: log.error('Failed to add access_log attribute to %s elb.', name) return False if czlb: _czlb = CrossZoneLoadBalancingAttribute() _czlb.enabled = czlb['enabled'] added_attr = conn.modify_lb_attribute(name, 'crossZoneLoadBalancing', _czlb.enabled) if added_attr: log.info('Added cross_zone_load_balancing attribute to %s elb.', name) else: log.error('Failed to add cross_zone_load_balancing attribute.') return False if cd: _cd = ConnectionDrainingAttribute() _cd.enabled = cd['enabled'] _cd.timeout = cd.get('timeout', 300) added_attr = conn.modify_lb_attribute(name, 'connectionDraining', _cd) if added_attr: log.info('Added connection_draining attribute to %s elb.', name) else: log.error('Failed to add connection_draining attribute.') return False if cs: _cs = ConnectionSettingAttribute() _cs.idle_timeout = cs.get('idle_timeout', 60) added_attr = conn.modify_lb_attribute(name, 'connectingSettings', _cs) if added_attr: log.info('Added connecting_settings attribute to %s elb.', name) else: log.error('Failed to add connecting_settings attribute.') return False return True def get_health_check(name, region=None, key=None, keyid=None, profile=None): ''' Get the health check configured for this ELB. CLI example: .. code-block:: bash salt myminion boto_elb.get_health_check myelb ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) retries = 30 while True: try: lb = conn.get_all_load_balancers(load_balancer_names=[name]) lb = lb[0] ret = odict.OrderedDict() hc = lb.health_check ret['interval'] = hc.interval ret['target'] = hc.target ret['healthy_threshold'] = hc.healthy_threshold ret['timeout'] = hc.timeout ret['unhealthy_threshold'] = hc.unhealthy_threshold return ret except boto.exception.BotoServerError as e: if retries and e.code == 'Throttling': log.debug('Throttled by AWS API, will retry in 5 seconds.') time.sleep(5) retries -= 1 continue log.error('ELB %s not found.', name, exc_info_on_logleve=logging.DEBUG) return {} def set_health_check(name, health_check, region=None, key=None, keyid=None, profile=None): ''' Set attributes on an ELB. CLI example to set attributes on an ELB: .. code-block:: bash salt myminion boto_elb.set_health_check myelb '{"target": "HTTP:80/"}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) retries = 30 hc = HealthCheck(**health_check) while True: try: conn.configure_health_check(name, hc) log.info('Configured health check on ELB %s', name) return True except boto.exception.BotoServerError as error: if retries and e.code == 'Throttling': log.debug('Throttled by AWS API, will retry in 5 seconds.') time.sleep(5) retries -= 1 continue log.exception('Failed to configure health check on ELB %s', name) return False def register_instances(name, instances, region=None, key=None, keyid=None, profile=None): ''' Register instances with an ELB. Instances is either a string instance id or a list of string instance id's. Returns: - ``True``: instance(s) registered successfully - ``False``: instance(s) failed to be registered CLI example: .. code-block:: bash salt myminion boto_elb.register_instances myelb instance_id salt myminion boto_elb.register_instances myelb "[instance_id,instance_id]" ''' # convert instances to list type, enabling consistent use of instances # variable throughout the register_instances method if isinstance(instances, six.string_types) or isinstance(instances, six.text_type): instances = [instances] conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: registered_instances = conn.register_instances(name, instances) except boto.exception.BotoServerError as error: log.warning(error) return False registered_instance_ids = [instance.id for instance in registered_instances] # register_failues is a set that will contain any instances that were not # able to be registered with the given ELB register_failures = set(instances).difference(set(registered_instance_ids)) if register_failures: log.warning('Instance(s): %s not registered with ELB %s.', list(register_failures), name) register_result = False else: register_result = True return register_result def set_instances(name, instances, test=False, region=None, key=None, keyid=None, profile=None): ''' Set the instances assigned to an ELB to exactly the list given CLI example: .. code-block:: bash salt myminion boto_elb.set_instances myelb region=us-east-1 instances="[instance_id,instance_id]" ''' ret = True current = set([i['instance_id'] for i in get_instance_health(name, region, key, keyid, profile)]) desired = set(instances) add = desired - current remove = current - desired if test: return bool(add or remove) if remove: if deregister_instances(name, list(remove), region, key, keyid, profile) is False: ret = False if add: if register_instances(name, list(add), region, key, keyid, profile) is False: ret = False return ret def get_instance_health(name, region=None, key=None, keyid=None, profile=None, instances=None): ''' Get a list of instances and their health state CLI example: .. code-block:: bash salt myminion boto_elb.get_instance_health myelb salt myminion boto_elb.get_instance_health myelb region=us-east-1 instances="[instance_id,instance_id]" ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: instance_states = conn.describe_instance_health(name, instances) ret = [] for _instance in instance_states: ret.append({'instance_id': _instance.instance_id, 'description': _instance.description, 'state': _instance.state, 'reason_code': _instance.reason_code }) return ret except boto.exception.BotoServerError as error: log.debug(error) return [] def create_policy(name, policy_name, policy_type, policy, region=None, key=None, keyid=None, profile=None): ''' Create an ELB policy. .. versionadded:: 2016.3.0 CLI example: .. code-block:: bash salt myminion boto_elb.create_policy myelb mypolicy LBCookieStickinessPolicyType '{"CookieExpirationPeriod": 3600}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not exists(name, region, key, keyid, profile): return False try: success = conn.create_lb_policy(name, policy_name, policy_type, policy) if success: log.info('Created policy %s on ELB %s', policy_name, name) return True else: log.error('Failed to create policy %s on ELB %s', policy_name, name) return False except boto.exception.BotoServerError as e: log.error('Failed to create policy %s on ELB %s: %s', policy_name, name, e.message, exc_info_on_loglevel=logging.DEBUG) return False def delete_policy(name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Delete an ELB policy. .. versionadded:: 2016.3.0 CLI example: .. code-block:: bash salt myminion boto_elb.delete_policy myelb mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not exists(name, region, key, keyid, profile): return True try: conn.delete_lb_policy(name, policy_name) log.info('Deleted policy %s on ELB %s', policy_name, name) return True except boto.exception.BotoServerError as e: log.error('Failed to delete policy %s on ELB %s: %s', policy_name, name, e.message, exc_info_on_loglevel=logging.DEBUG) return False def set_listener_policy(name, port, policies=None, region=None, key=None, keyid=None, profile=None): ''' Set the policies of an ELB listener. .. versionadded:: 2016.3.0 CLI example: .. code-block:: Bash salt myminion boto_elb.set_listener_policy myelb 443 "[policy1,policy2]" ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not exists(name, region, key, keyid, profile): return True if policies is None: policies = [] try: conn.set_lb_policies_of_listener(name, port, policies) log.info('Set policies %s on ELB %s listener %s', policies, name, port) except boto.exception.BotoServerError as e: log.info('Failed to set policy %s on ELB %s listener %s: %s', policies, name, port, e.message, exc_info_on_loglevel=logging.DEBUG) return False return True def set_backend_policy(name, port, policies=None, region=None, key=None, keyid=None, profile=None): ''' Set the policies of an ELB backend server. CLI example: salt myminion boto_elb.set_backend_policy myelb 443 "[policy1,policy2]" ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not exists(name, region, key, keyid, profile): return True if policies is None: policies = [] try: conn.set_lb_policies_of_backend_server(name, port, policies) log.info('Set policies %s on ELB %s backend server %s', policies, name, port) except boto.exception.BotoServerError as e: log.info('Failed to set policy %s on ELB %s backend server %s: %s', policies, name, port, e.message, exc_info_on_loglevel=logging.DEBUG) return False return True def set_tags(name, tags, region=None, key=None, keyid=None, profile=None): ''' Add the tags on an ELB .. versionadded:: 2016.3.0 name name of the ELB tags dict of name/value pair tags CLI Example: .. code-block:: bash salt myminion boto_elb.set_tags my-elb-name "{'Tag1': 'Value', 'Tag2': 'Another Value'}" ''' if exists(name, region, key, keyid, profile): conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) ret = _add_tags(conn, name, tags) return ret else: return False def delete_tags(name, tags, region=None, key=None, keyid=None, profile=None): ''' Add the tags on an ELB name name of the ELB tags list of tags to remove CLI Example: .. code-block:: bash salt myminion boto_elb.delete_tags my-elb-name ['TagToRemove1', 'TagToRemove2'] ''' if exists(name, region, key, keyid, profile): conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) ret = _remove_tags(conn, name, tags) return ret else: return False def _build_tag_param_list(params, tags): ''' helper function to build a tag parameter list to send ''' keys = sorted(tags.keys()) i = 1 for key in keys: value = tags[key] params['Tags.member.{0}.Key'.format(i)] = key if value is not None: params['Tags.member.{0}.Value'.format(i)] = value i += 1 def _get_all_tags(conn, load_balancer_names=None): ''' Retrieve all the metadata tags associated with your ELB(s). :type load_balancer_names: list :param load_balancer_names: An optional list of load balancer names. :rtype: list :return: A list of :class:`boto.ec2.elb.tag.Tag` objects ''' params = {} if load_balancer_names: conn.build_list_params(params, load_balancer_names, 'LoadBalancerNames.member.%d') tags = conn.get_object( 'DescribeTags', params, __utils__['boto_elb_tag.get_tag_descriptions'](), verb='POST' ) if tags[load_balancer_names]: return tags[load_balancer_names] else: return None def _add_tags(conn, load_balancer_names, tags): ''' Create new metadata tags for the specified resource ids. :type load_balancer_names: list :param load_balancer_names: A list of load balancer names. :type tags: dict :param tags: A dictionary containing the name/value pairs. If you want to create only a tag name, the value for that tag should be the empty string (e.g. ''). ''' params = {} conn.build_list_params(params, load_balancer_names, 'LoadBalancerNames.member.%d') _build_tag_param_list(params, tags) return conn.get_status('AddTags', params, verb='POST') def _remove_tags(conn, load_balancer_names, tags): ''' Delete metadata tags for the specified resource ids. :type load_balancer_names: list :param load_balancer_names: A list of load balancer names. :type tags: list :param tags: A list containing just tag names for the tags to be deleted. ''' params = {} conn.build_list_params(params, load_balancer_names, 'LoadBalancerNames.member.%d') conn.build_list_params(params, tags, 'Tags.member.%d.Key') return conn.get_status('RemoveTags', params, verb='POST')
saltstack/salt
salt/modules/boto_elb.py
set_instances
python
def set_instances(name, instances, test=False, region=None, key=None, keyid=None, profile=None): ''' Set the instances assigned to an ELB to exactly the list given CLI example: .. code-block:: bash salt myminion boto_elb.set_instances myelb region=us-east-1 instances="[instance_id,instance_id]" ''' ret = True current = set([i['instance_id'] for i in get_instance_health(name, region, key, keyid, profile)]) desired = set(instances) add = desired - current remove = current - desired if test: return bool(add or remove) if remove: if deregister_instances(name, list(remove), region, key, keyid, profile) is False: ret = False if add: if register_instances(name, list(add), region, key, keyid, profile) is False: ret = False return ret
Set the instances assigned to an ELB to exactly the list given CLI example: .. code-block:: bash salt myminion boto_elb.set_instances myelb region=us-east-1 instances="[instance_id,instance_id]"
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_elb.py#L792-L816
[ "def register_instances(name, instances, region=None, key=None, keyid=None,\n profile=None):\n '''\n Register instances with an ELB. Instances is either a string\n instance id or a list of string instance id's.\n\n Returns:\n\n - ``True``: instance(s) registered successfully\n - ``False``: instance(s) failed to be registered\n\n CLI example:\n\n .. code-block:: bash\n\n salt myminion boto_elb.register_instances myelb instance_id\n salt myminion boto_elb.register_instances myelb \"[instance_id,instance_id]\"\n '''\n # convert instances to list type, enabling consistent use of instances\n # variable throughout the register_instances method\n if isinstance(instances, six.string_types) or isinstance(instances, six.text_type):\n instances = [instances]\n conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)\n\n try:\n registered_instances = conn.register_instances(name, instances)\n except boto.exception.BotoServerError as error:\n log.warning(error)\n return False\n registered_instance_ids = [instance.id for instance in\n registered_instances]\n # register_failues is a set that will contain any instances that were not\n # able to be registered with the given ELB\n register_failures = set(instances).difference(set(registered_instance_ids))\n if register_failures:\n log.warning('Instance(s): %s not registered with ELB %s.',\n list(register_failures), name)\n register_result = False\n else:\n register_result = True\n return register_result\n", "def deregister_instances(name, instances, region=None, key=None, keyid=None,\n profile=None):\n '''\n Deregister instances with an ELB. Instances is either a string\n instance id or a list of string instance id's.\n\n Returns:\n\n - ``True``: instance(s) deregistered successfully\n - ``False``: instance(s) failed to be deregistered\n - ``None``: instance(s) not valid or not registered, no action taken\n\n CLI example:\n\n .. code-block:: bash\n\n salt myminion boto_elb.deregister_instances myelb instance_id\n salt myminion boto_elb.deregister_instances myelb \"[instance_id, instance_id]\"\n '''\n # convert instances to list type, enabling consistent use of instances\n # variable throughout the deregister_instances method\n if isinstance(instances, six.string_types) or isinstance(instances, six.text_type):\n instances = [instances]\n conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)\n\n try:\n registered_instances = conn.deregister_instances(name, instances)\n except boto.exception.BotoServerError as error:\n # if the instance(s) given as an argument are not members of the ELB\n # boto returns error.error_code == 'InvalidInstance'\n # deregister_instances returns \"None\" because the instances are\n # effectively deregistered from ELB\n if error.error_code == 'InvalidInstance':\n log.warning(\n 'One or more of instance(s) %s are not part of ELB %s. '\n 'deregister_instances not performed.', instances, name\n )\n return None\n else:\n log.warning(error)\n return False\n registered_instance_ids = [instance.id for instance in\n registered_instances]\n # deregister_failures is a set that will contain any instances that were\n # unable to be deregistered from the given ELB\n deregister_failures = set(instances).intersection(set(registered_instance_ids))\n if deregister_failures:\n log.warning(\n 'Instance(s): %s not deregistered from ELB %s.',\n list(deregister_failures), name\n )\n deregister_result = False\n else:\n deregister_result = True\n return deregister_result\n", "def get_instance_health(name, region=None, key=None, keyid=None, profile=None, instances=None):\n '''\n Get a list of instances and their health state\n\n CLI example:\n\n .. code-block:: bash\n\n salt myminion boto_elb.get_instance_health myelb\n salt myminion boto_elb.get_instance_health myelb region=us-east-1 instances=\"[instance_id,instance_id]\"\n '''\n conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)\n\n try:\n instance_states = conn.describe_instance_health(name, instances)\n ret = []\n for _instance in instance_states:\n ret.append({'instance_id': _instance.instance_id,\n 'description': _instance.description,\n 'state': _instance.state,\n 'reason_code': _instance.reason_code\n })\n return ret\n except boto.exception.BotoServerError as error:\n log.debug(error)\n return []\n" ]
# -*- coding: utf-8 -*- ''' Connection module for Amazon ELB .. versionadded:: 2014.7.0 :configuration: This module accepts explicit elb credentials but can also utilize IAM roles assigned to the instance through Instance Profiles. Dynamic credentials are then automatically obtained from AWS API and no further configuration is necessary. More Information available at: .. code-block:: text http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/iam-roles-for-amazon-ec2.html If IAM roles are not used you need to specify them either in a pillar or in the minion's config file: .. code-block:: yaml elb.keyid: GKTADJGHEIQSXMKKRBJ08H elb.key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs A region may also be specified in the configuration: .. code-block:: yaml elb.region: us-east-1 If a region is not specified, the default is us-east-1. It's also possible to specify key, keyid and region via a profile, either as a passed in dict, or as a string to pull from pillars or minion config: .. code-block:: yaml myprofile: keyid: GKTADJGHEIQSXMKKRBJ08H key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs region: us-east-1 :depends: boto >= 2.33.0 ''' # keep lint from choking on _get_conn and _cache_id # pylint: disable=E0602 from __future__ import absolute_import, print_function, unicode_literals # Import Python libs import logging import time log = logging.getLogger(__name__) # Import Salt libs import salt.utils.json import salt.utils.odict as odict import salt.utils.versions # Import third party libs from salt.ext import six try: import boto import boto.ec2 # pylint: enable=unused-import from boto.ec2.elb import HealthCheck from boto.ec2.elb.attributes import AccessLogAttribute from boto.ec2.elb.attributes import ConnectionDrainingAttribute from boto.ec2.elb.attributes import ConnectionSettingAttribute from boto.ec2.elb.attributes import CrossZoneLoadBalancingAttribute logging.getLogger('boto').setLevel(logging.CRITICAL) HAS_BOTO = True except ImportError: HAS_BOTO = False def __virtual__(): ''' Only load if boto libraries exist. ''' # connection settings were added in 2.33.0 has_boto_reqs = salt.utils.versions.check_boto_reqs( boto_ver='2.33.0', check_boto3=False ) if has_boto_reqs is True: __utils__['boto.assign_funcs'](__name__, 'elb', module='ec2.elb', pack=__salt__) return has_boto_reqs def exists(name, region=None, key=None, keyid=None, profile=None): ''' Check to see if an ELB exists. CLI example: .. code-block:: bash salt myminion boto_elb.exists myelb region=us-east-1 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: elb = conn.get_all_load_balancers(load_balancer_names=[name]) if elb: return True else: log.debug('The load balancer does not exist in region %s', region) return False except boto.exception.BotoServerError as error: log.warning(error) return False def get_all_elbs(region=None, key=None, keyid=None, profile=None): ''' Return all load balancers associated with an account CLI example: .. code-block:: bash salt myminion boto_elb.get_all_elbs region=us-east-1 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: return [e for e in conn.get_all_load_balancers()] except boto.exception.BotoServerError as error: log.warning(error) return [] def list_elbs(region=None, key=None, keyid=None, profile=None): ''' Return names of all load balancers associated with an account CLI example: .. code-block:: bash salt myminion boto_elb.list_elbs region=us-east-1 ''' return [e.name for e in get_all_elbs(region=region, key=key, keyid=keyid, profile=profile)] def get_elb_config(name, region=None, key=None, keyid=None, profile=None): ''' Get an ELB configuration. CLI example: .. code-block:: bash salt myminion boto_elb.exists myelb region=us-east-1 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) retries = 30 while retries: try: lb = conn.get_all_load_balancers(load_balancer_names=[name]) lb = lb[0] ret = {} ret['availability_zones'] = lb.availability_zones listeners = [] for _listener in lb.listeners: listener_dict = {} listener_dict['elb_port'] = _listener.load_balancer_port listener_dict['elb_protocol'] = _listener.protocol listener_dict['instance_port'] = _listener.instance_port listener_dict['instance_protocol'] = _listener.instance_protocol listener_dict['policies'] = _listener.policy_names if _listener.ssl_certificate_id: listener_dict['certificate'] = _listener.ssl_certificate_id listeners.append(listener_dict) ret['listeners'] = listeners backends = [] for _backend in lb.backends: bs_dict = {} bs_dict['instance_port'] = _backend.instance_port bs_dict['policies'] = [p.policy_name for p in _backend.policies] backends.append(bs_dict) ret['backends'] = backends ret['subnets'] = lb.subnets ret['security_groups'] = lb.security_groups ret['scheme'] = lb.scheme ret['dns_name'] = lb.dns_name ret['tags'] = _get_all_tags(conn, name) lb_policy_lists = [ lb.policies.app_cookie_stickiness_policies, lb.policies.lb_cookie_stickiness_policies, lb.policies.other_policies ] policies = [] for policy_list in lb_policy_lists: policies += [p.policy_name for p in policy_list] ret['policies'] = policies return ret except boto.exception.BotoServerError as error: if error.error_code == 'Throttling': log.debug('Throttled by AWS API, will retry in 5 seconds.') time.sleep(5) retries -= 1 continue log.error('Error fetching config for ELB %s: %s', name, error.message) log.error(error) return {} return {} def listener_dict_to_tuple(listener): ''' Convert an ELB listener dict into a listener tuple used by certain parts of the AWS ELB API. CLI example: .. code-block:: bash salt myminion boto_elb.listener_dict_to_tuple '{"elb_port":80,"instance_port":80,"elb_protocol":"HTTP"}' ''' # We define all listeners as complex listeners. if 'instance_protocol' not in listener: instance_protocol = listener['elb_protocol'].upper() else: instance_protocol = listener['instance_protocol'].upper() listener_tuple = [listener['elb_port'], listener['instance_port'], listener['elb_protocol'], instance_protocol] if 'certificate' in listener: listener_tuple.append(listener['certificate']) return tuple(listener_tuple) def create(name, availability_zones, listeners, subnets=None, security_groups=None, scheme='internet-facing', region=None, key=None, keyid=None, profile=None): ''' Create an ELB CLI example to create an ELB: .. code-block:: bash salt myminion boto_elb.create myelb '["us-east-1a", "us-east-1e"]' '{"elb_port": 443, "elb_protocol": "HTTPS", ...}' region=us-east-1 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if exists(name, region, key, keyid, profile): return True if isinstance(availability_zones, six.string_types): availability_zones = salt.utils.json.loads(availability_zones) if isinstance(listeners, six.string_types): listeners = salt.utils.json.loads(listeners) _complex_listeners = [] for listener in listeners: _complex_listeners.append(listener_dict_to_tuple(listener)) try: lb = conn.create_load_balancer(name=name, zones=availability_zones, subnets=subnets, security_groups=security_groups, scheme=scheme, complex_listeners=_complex_listeners) if lb: log.info('Created ELB %s', name) return True else: log.error('Failed to create ELB %s', name) return False except boto.exception.BotoServerError as error: log.error('Failed to create ELB %s: %s: %s', name, error.error_code, error.message, exc_info_on_loglevel=logging.DEBUG) return False def delete(name, region=None, key=None, keyid=None, profile=None): ''' Delete an ELB. CLI example to delete an ELB: .. code-block:: bash salt myminion boto_elb.delete myelb region=us-east-1 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not exists(name, region, key, keyid, profile): return True try: conn.delete_load_balancer(name) log.info('Deleted ELB %s.', name) return True except boto.exception.BotoServerError as error: log.error('Failed to delete ELB %s', name, exc_info_on_loglevel=logging.DEBUG) return False def create_listeners(name, listeners, region=None, key=None, keyid=None, profile=None): ''' Create listeners on an ELB. CLI example: .. code-block:: bash salt myminion boto_elb.create_listeners myelb '[["HTTPS", "HTTP", 443, 80, "arn:aws:iam::11 11111:server-certificate/mycert"]]' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if isinstance(listeners, six.string_types): listeners = salt.utils.json.loads(listeners) _complex_listeners = [] for listener in listeners: _complex_listeners.append(listener_dict_to_tuple(listener)) try: conn.create_load_balancer_listeners(name, [], _complex_listeners) log.info('Created ELB listeners on %s', name) return True except boto.exception.BotoServerError as error: log.error('Failed to create ELB listeners on %s: %s', name, error, exc_info_on_loglevel=logging.DEBUG) return False def delete_listeners(name, ports, region=None, key=None, keyid=None, profile=None): ''' Delete listeners on an ELB. CLI example: .. code-block:: bash salt myminion boto_elb.delete_listeners myelb '[80,443]' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if isinstance(ports, six.string_types): ports = salt.utils.json.loads(ports) try: conn.delete_load_balancer_listeners(name, ports) log.info('Deleted ELB listeners on %s', name) return True except boto.exception.BotoServerError as error: log.error('Failed to delete ELB listeners on %s: %s', name, error, exc_info_on_loglevel=logging.DEBUG) return False def apply_security_groups(name, security_groups, region=None, key=None, keyid=None, profile=None): ''' Apply security groups to ELB. CLI example: .. code-block:: bash salt myminion boto_elb.apply_security_groups myelb '["mysecgroup1"]' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if isinstance(security_groups, six.string_types): security_groups = salt.utils.json.loads(security_groups) try: conn.apply_security_groups_to_lb(name, security_groups) log.info('Applied security_groups on ELB %s', name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to appply security_groups on ELB %s: %s', name, e.message) return False def enable_availability_zones(name, availability_zones, region=None, key=None, keyid=None, profile=None): ''' Enable availability zones for ELB. CLI example: .. code-block:: bash salt myminion boto_elb.enable_availability_zones myelb '["us-east-1a"]' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if isinstance(availability_zones, six.string_types): availability_zones = salt.utils.json.loads(availability_zones) try: conn.enable_availability_zones(name, availability_zones) log.info('Enabled availability_zones on ELB %s', name) return True except boto.exception.BotoServerError as error: log.error('Failed to enable availability_zones on ELB %s: %s', name, error) return False def disable_availability_zones(name, availability_zones, region=None, key=None, keyid=None, profile=None): ''' Disable availability zones for ELB. CLI example: .. code-block:: bash salt myminion boto_elb.disable_availability_zones myelb '["us-east-1a"]' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if isinstance(availability_zones, six.string_types): availability_zones = salt.utils.json.loads(availability_zones) try: conn.disable_availability_zones(name, availability_zones) log.info('Disabled availability_zones on ELB %s', name) return True except boto.exception.BotoServerError as error: log.error('Failed to disable availability_zones on ELB %s: %s', name, error, exc_info_on_loglevel=logging.DEBUG) return False def attach_subnets(name, subnets, region=None, key=None, keyid=None, profile=None): ''' Attach ELB to subnets. CLI example: .. code-block:: bash salt myminion boto_elb.attach_subnets myelb '["mysubnet"]' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if isinstance(subnets, six.string_types): subnets = salt.utils.json.loads(subnets) try: conn.attach_lb_to_subnets(name, subnets) log.info('Attached ELB %s on subnets.', name) return True except boto.exception.BotoServerError as error: log.error('Failed to attach ELB %s on subnets: %s', name, error, exc_info_on_loglevel=logging.DEBUG) return False def detach_subnets(name, subnets, region=None, key=None, keyid=None, profile=None): ''' Detach ELB from subnets. CLI example: .. code-block:: bash salt myminion boto_elb.detach_subnets myelb '["mysubnet"]' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if isinstance(subnets, six.string_types): subnets = salt.utils.json.loads(subnets) try: conn.detach_lb_from_subnets(name, subnets) log.info('Detached ELB %s from subnets.', name) return True except boto.exception.BotoServerError as error: log.error('Failed to detach ELB %s from subnets: %s', name, error, exc_info_on_loglevel=logging.DEBUG) return False def get_attributes(name, region=None, key=None, keyid=None, profile=None): ''' Check to see if attributes are set on an ELB. CLI example: .. code-block:: bash salt myminion boto_elb.get_attributes myelb ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) retries = 30 while retries: try: lbattrs = conn.get_all_lb_attributes(name) ret = odict.OrderedDict() ret['access_log'] = odict.OrderedDict() ret['cross_zone_load_balancing'] = odict.OrderedDict() ret['connection_draining'] = odict.OrderedDict() ret['connecting_settings'] = odict.OrderedDict() al = lbattrs.access_log czlb = lbattrs.cross_zone_load_balancing cd = lbattrs.connection_draining cs = lbattrs.connecting_settings ret['access_log']['enabled'] = al.enabled ret['access_log']['s3_bucket_name'] = al.s3_bucket_name ret['access_log']['s3_bucket_prefix'] = al.s3_bucket_prefix ret['access_log']['emit_interval'] = al.emit_interval ret['cross_zone_load_balancing']['enabled'] = czlb.enabled ret['connection_draining']['enabled'] = cd.enabled ret['connection_draining']['timeout'] = cd.timeout ret['connecting_settings']['idle_timeout'] = cs.idle_timeout return ret except boto.exception.BotoServerError as e: if e.error_code == 'Throttling': log.debug("Throttled by AWS API, will retry in 5 seconds...") time.sleep(5) retries -= 1 continue log.error('ELB %s does not exist: %s', name, e.message) return {} return {} def set_attributes(name, attributes, region=None, key=None, keyid=None, profile=None): ''' Set attributes on an ELB. name (string) Name of the ELB instance to set attributes for attributes A dict of attributes to set. Valid attributes are: access_log (dict) enabled (bool) Enable storage of access logs. s3_bucket_name (string) The name of the S3 bucket to place logs. s3_bucket_prefix (string) Prefix for the log file name. emit_interval (int) Interval for storing logs in S3 in minutes. Valid values are 5 and 60. connection_draining (dict) enabled (bool) Enable connection draining. timeout (int) Maximum allowed time in seconds for sending existing connections to an instance that is deregistering or unhealthy. Default is 300. cross_zone_load_balancing (dict) enabled (bool) Enable cross-zone load balancing. CLI example to set attributes on an ELB: .. code-block:: bash salt myminion boto_elb.set_attributes myelb '{"access_log": {"enabled": "true", "s3_bucket_name": "mybucket", "s3_bucket_prefix": "mylogs/", "emit_interval": "5"}}' region=us-east-1 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) al = attributes.get('access_log', {}) czlb = attributes.get('cross_zone_load_balancing', {}) cd = attributes.get('connection_draining', {}) cs = attributes.get('connecting_settings', {}) if not al and not czlb and not cd and not cs: log.error('No supported attributes for ELB.') return False if al: _al = AccessLogAttribute() _al.enabled = al.get('enabled', False) if not _al.enabled: msg = 'Access log attribute configured, but enabled config missing' log.error(msg) return False _al.s3_bucket_name = al.get('s3_bucket_name', None) _al.s3_bucket_prefix = al.get('s3_bucket_prefix', None) _al.emit_interval = al.get('emit_interval', None) added_attr = conn.modify_lb_attribute(name, 'accessLog', _al) if added_attr: log.info('Added access_log attribute to %s elb.', name) else: log.error('Failed to add access_log attribute to %s elb.', name) return False if czlb: _czlb = CrossZoneLoadBalancingAttribute() _czlb.enabled = czlb['enabled'] added_attr = conn.modify_lb_attribute(name, 'crossZoneLoadBalancing', _czlb.enabled) if added_attr: log.info('Added cross_zone_load_balancing attribute to %s elb.', name) else: log.error('Failed to add cross_zone_load_balancing attribute.') return False if cd: _cd = ConnectionDrainingAttribute() _cd.enabled = cd['enabled'] _cd.timeout = cd.get('timeout', 300) added_attr = conn.modify_lb_attribute(name, 'connectionDraining', _cd) if added_attr: log.info('Added connection_draining attribute to %s elb.', name) else: log.error('Failed to add connection_draining attribute.') return False if cs: _cs = ConnectionSettingAttribute() _cs.idle_timeout = cs.get('idle_timeout', 60) added_attr = conn.modify_lb_attribute(name, 'connectingSettings', _cs) if added_attr: log.info('Added connecting_settings attribute to %s elb.', name) else: log.error('Failed to add connecting_settings attribute.') return False return True def get_health_check(name, region=None, key=None, keyid=None, profile=None): ''' Get the health check configured for this ELB. CLI example: .. code-block:: bash salt myminion boto_elb.get_health_check myelb ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) retries = 30 while True: try: lb = conn.get_all_load_balancers(load_balancer_names=[name]) lb = lb[0] ret = odict.OrderedDict() hc = lb.health_check ret['interval'] = hc.interval ret['target'] = hc.target ret['healthy_threshold'] = hc.healthy_threshold ret['timeout'] = hc.timeout ret['unhealthy_threshold'] = hc.unhealthy_threshold return ret except boto.exception.BotoServerError as e: if retries and e.code == 'Throttling': log.debug('Throttled by AWS API, will retry in 5 seconds.') time.sleep(5) retries -= 1 continue log.error('ELB %s not found.', name, exc_info_on_logleve=logging.DEBUG) return {} def set_health_check(name, health_check, region=None, key=None, keyid=None, profile=None): ''' Set attributes on an ELB. CLI example to set attributes on an ELB: .. code-block:: bash salt myminion boto_elb.set_health_check myelb '{"target": "HTTP:80/"}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) retries = 30 hc = HealthCheck(**health_check) while True: try: conn.configure_health_check(name, hc) log.info('Configured health check on ELB %s', name) return True except boto.exception.BotoServerError as error: if retries and e.code == 'Throttling': log.debug('Throttled by AWS API, will retry in 5 seconds.') time.sleep(5) retries -= 1 continue log.exception('Failed to configure health check on ELB %s', name) return False def register_instances(name, instances, region=None, key=None, keyid=None, profile=None): ''' Register instances with an ELB. Instances is either a string instance id or a list of string instance id's. Returns: - ``True``: instance(s) registered successfully - ``False``: instance(s) failed to be registered CLI example: .. code-block:: bash salt myminion boto_elb.register_instances myelb instance_id salt myminion boto_elb.register_instances myelb "[instance_id,instance_id]" ''' # convert instances to list type, enabling consistent use of instances # variable throughout the register_instances method if isinstance(instances, six.string_types) or isinstance(instances, six.text_type): instances = [instances] conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: registered_instances = conn.register_instances(name, instances) except boto.exception.BotoServerError as error: log.warning(error) return False registered_instance_ids = [instance.id for instance in registered_instances] # register_failues is a set that will contain any instances that were not # able to be registered with the given ELB register_failures = set(instances).difference(set(registered_instance_ids)) if register_failures: log.warning('Instance(s): %s not registered with ELB %s.', list(register_failures), name) register_result = False else: register_result = True return register_result def deregister_instances(name, instances, region=None, key=None, keyid=None, profile=None): ''' Deregister instances with an ELB. Instances is either a string instance id or a list of string instance id's. Returns: - ``True``: instance(s) deregistered successfully - ``False``: instance(s) failed to be deregistered - ``None``: instance(s) not valid or not registered, no action taken CLI example: .. code-block:: bash salt myminion boto_elb.deregister_instances myelb instance_id salt myminion boto_elb.deregister_instances myelb "[instance_id, instance_id]" ''' # convert instances to list type, enabling consistent use of instances # variable throughout the deregister_instances method if isinstance(instances, six.string_types) or isinstance(instances, six.text_type): instances = [instances] conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: registered_instances = conn.deregister_instances(name, instances) except boto.exception.BotoServerError as error: # if the instance(s) given as an argument are not members of the ELB # boto returns error.error_code == 'InvalidInstance' # deregister_instances returns "None" because the instances are # effectively deregistered from ELB if error.error_code == 'InvalidInstance': log.warning( 'One or more of instance(s) %s are not part of ELB %s. ' 'deregister_instances not performed.', instances, name ) return None else: log.warning(error) return False registered_instance_ids = [instance.id for instance in registered_instances] # deregister_failures is a set that will contain any instances that were # unable to be deregistered from the given ELB deregister_failures = set(instances).intersection(set(registered_instance_ids)) if deregister_failures: log.warning( 'Instance(s): %s not deregistered from ELB %s.', list(deregister_failures), name ) deregister_result = False else: deregister_result = True return deregister_result def get_instance_health(name, region=None, key=None, keyid=None, profile=None, instances=None): ''' Get a list of instances and their health state CLI example: .. code-block:: bash salt myminion boto_elb.get_instance_health myelb salt myminion boto_elb.get_instance_health myelb region=us-east-1 instances="[instance_id,instance_id]" ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: instance_states = conn.describe_instance_health(name, instances) ret = [] for _instance in instance_states: ret.append({'instance_id': _instance.instance_id, 'description': _instance.description, 'state': _instance.state, 'reason_code': _instance.reason_code }) return ret except boto.exception.BotoServerError as error: log.debug(error) return [] def create_policy(name, policy_name, policy_type, policy, region=None, key=None, keyid=None, profile=None): ''' Create an ELB policy. .. versionadded:: 2016.3.0 CLI example: .. code-block:: bash salt myminion boto_elb.create_policy myelb mypolicy LBCookieStickinessPolicyType '{"CookieExpirationPeriod": 3600}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not exists(name, region, key, keyid, profile): return False try: success = conn.create_lb_policy(name, policy_name, policy_type, policy) if success: log.info('Created policy %s on ELB %s', policy_name, name) return True else: log.error('Failed to create policy %s on ELB %s', policy_name, name) return False except boto.exception.BotoServerError as e: log.error('Failed to create policy %s on ELB %s: %s', policy_name, name, e.message, exc_info_on_loglevel=logging.DEBUG) return False def delete_policy(name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Delete an ELB policy. .. versionadded:: 2016.3.0 CLI example: .. code-block:: bash salt myminion boto_elb.delete_policy myelb mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not exists(name, region, key, keyid, profile): return True try: conn.delete_lb_policy(name, policy_name) log.info('Deleted policy %s on ELB %s', policy_name, name) return True except boto.exception.BotoServerError as e: log.error('Failed to delete policy %s on ELB %s: %s', policy_name, name, e.message, exc_info_on_loglevel=logging.DEBUG) return False def set_listener_policy(name, port, policies=None, region=None, key=None, keyid=None, profile=None): ''' Set the policies of an ELB listener. .. versionadded:: 2016.3.0 CLI example: .. code-block:: Bash salt myminion boto_elb.set_listener_policy myelb 443 "[policy1,policy2]" ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not exists(name, region, key, keyid, profile): return True if policies is None: policies = [] try: conn.set_lb_policies_of_listener(name, port, policies) log.info('Set policies %s on ELB %s listener %s', policies, name, port) except boto.exception.BotoServerError as e: log.info('Failed to set policy %s on ELB %s listener %s: %s', policies, name, port, e.message, exc_info_on_loglevel=logging.DEBUG) return False return True def set_backend_policy(name, port, policies=None, region=None, key=None, keyid=None, profile=None): ''' Set the policies of an ELB backend server. CLI example: salt myminion boto_elb.set_backend_policy myelb 443 "[policy1,policy2]" ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not exists(name, region, key, keyid, profile): return True if policies is None: policies = [] try: conn.set_lb_policies_of_backend_server(name, port, policies) log.info('Set policies %s on ELB %s backend server %s', policies, name, port) except boto.exception.BotoServerError as e: log.info('Failed to set policy %s on ELB %s backend server %s: %s', policies, name, port, e.message, exc_info_on_loglevel=logging.DEBUG) return False return True def set_tags(name, tags, region=None, key=None, keyid=None, profile=None): ''' Add the tags on an ELB .. versionadded:: 2016.3.0 name name of the ELB tags dict of name/value pair tags CLI Example: .. code-block:: bash salt myminion boto_elb.set_tags my-elb-name "{'Tag1': 'Value', 'Tag2': 'Another Value'}" ''' if exists(name, region, key, keyid, profile): conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) ret = _add_tags(conn, name, tags) return ret else: return False def delete_tags(name, tags, region=None, key=None, keyid=None, profile=None): ''' Add the tags on an ELB name name of the ELB tags list of tags to remove CLI Example: .. code-block:: bash salt myminion boto_elb.delete_tags my-elb-name ['TagToRemove1', 'TagToRemove2'] ''' if exists(name, region, key, keyid, profile): conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) ret = _remove_tags(conn, name, tags) return ret else: return False def _build_tag_param_list(params, tags): ''' helper function to build a tag parameter list to send ''' keys = sorted(tags.keys()) i = 1 for key in keys: value = tags[key] params['Tags.member.{0}.Key'.format(i)] = key if value is not None: params['Tags.member.{0}.Value'.format(i)] = value i += 1 def _get_all_tags(conn, load_balancer_names=None): ''' Retrieve all the metadata tags associated with your ELB(s). :type load_balancer_names: list :param load_balancer_names: An optional list of load balancer names. :rtype: list :return: A list of :class:`boto.ec2.elb.tag.Tag` objects ''' params = {} if load_balancer_names: conn.build_list_params(params, load_balancer_names, 'LoadBalancerNames.member.%d') tags = conn.get_object( 'DescribeTags', params, __utils__['boto_elb_tag.get_tag_descriptions'](), verb='POST' ) if tags[load_balancer_names]: return tags[load_balancer_names] else: return None def _add_tags(conn, load_balancer_names, tags): ''' Create new metadata tags for the specified resource ids. :type load_balancer_names: list :param load_balancer_names: A list of load balancer names. :type tags: dict :param tags: A dictionary containing the name/value pairs. If you want to create only a tag name, the value for that tag should be the empty string (e.g. ''). ''' params = {} conn.build_list_params(params, load_balancer_names, 'LoadBalancerNames.member.%d') _build_tag_param_list(params, tags) return conn.get_status('AddTags', params, verb='POST') def _remove_tags(conn, load_balancer_names, tags): ''' Delete metadata tags for the specified resource ids. :type load_balancer_names: list :param load_balancer_names: A list of load balancer names. :type tags: list :param tags: A list containing just tag names for the tags to be deleted. ''' params = {} conn.build_list_params(params, load_balancer_names, 'LoadBalancerNames.member.%d') conn.build_list_params(params, tags, 'Tags.member.%d.Key') return conn.get_status('RemoveTags', params, verb='POST')
saltstack/salt
salt/modules/boto_elb.py
get_instance_health
python
def get_instance_health(name, region=None, key=None, keyid=None, profile=None, instances=None): ''' Get a list of instances and their health state CLI example: .. code-block:: bash salt myminion boto_elb.get_instance_health myelb salt myminion boto_elb.get_instance_health myelb region=us-east-1 instances="[instance_id,instance_id]" ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: instance_states = conn.describe_instance_health(name, instances) ret = [] for _instance in instance_states: ret.append({'instance_id': _instance.instance_id, 'description': _instance.description, 'state': _instance.state, 'reason_code': _instance.reason_code }) return ret except boto.exception.BotoServerError as error: log.debug(error) return []
Get a list of instances and their health state CLI example: .. code-block:: bash salt myminion boto_elb.get_instance_health myelb salt myminion boto_elb.get_instance_health myelb region=us-east-1 instances="[instance_id,instance_id]"
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_elb.py#L819-L844
null
# -*- coding: utf-8 -*- ''' Connection module for Amazon ELB .. versionadded:: 2014.7.0 :configuration: This module accepts explicit elb credentials but can also utilize IAM roles assigned to the instance through Instance Profiles. Dynamic credentials are then automatically obtained from AWS API and no further configuration is necessary. More Information available at: .. code-block:: text http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/iam-roles-for-amazon-ec2.html If IAM roles are not used you need to specify them either in a pillar or in the minion's config file: .. code-block:: yaml elb.keyid: GKTADJGHEIQSXMKKRBJ08H elb.key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs A region may also be specified in the configuration: .. code-block:: yaml elb.region: us-east-1 If a region is not specified, the default is us-east-1. It's also possible to specify key, keyid and region via a profile, either as a passed in dict, or as a string to pull from pillars or minion config: .. code-block:: yaml myprofile: keyid: GKTADJGHEIQSXMKKRBJ08H key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs region: us-east-1 :depends: boto >= 2.33.0 ''' # keep lint from choking on _get_conn and _cache_id # pylint: disable=E0602 from __future__ import absolute_import, print_function, unicode_literals # Import Python libs import logging import time log = logging.getLogger(__name__) # Import Salt libs import salt.utils.json import salt.utils.odict as odict import salt.utils.versions # Import third party libs from salt.ext import six try: import boto import boto.ec2 # pylint: enable=unused-import from boto.ec2.elb import HealthCheck from boto.ec2.elb.attributes import AccessLogAttribute from boto.ec2.elb.attributes import ConnectionDrainingAttribute from boto.ec2.elb.attributes import ConnectionSettingAttribute from boto.ec2.elb.attributes import CrossZoneLoadBalancingAttribute logging.getLogger('boto').setLevel(logging.CRITICAL) HAS_BOTO = True except ImportError: HAS_BOTO = False def __virtual__(): ''' Only load if boto libraries exist. ''' # connection settings were added in 2.33.0 has_boto_reqs = salt.utils.versions.check_boto_reqs( boto_ver='2.33.0', check_boto3=False ) if has_boto_reqs is True: __utils__['boto.assign_funcs'](__name__, 'elb', module='ec2.elb', pack=__salt__) return has_boto_reqs def exists(name, region=None, key=None, keyid=None, profile=None): ''' Check to see if an ELB exists. CLI example: .. code-block:: bash salt myminion boto_elb.exists myelb region=us-east-1 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: elb = conn.get_all_load_balancers(load_balancer_names=[name]) if elb: return True else: log.debug('The load balancer does not exist in region %s', region) return False except boto.exception.BotoServerError as error: log.warning(error) return False def get_all_elbs(region=None, key=None, keyid=None, profile=None): ''' Return all load balancers associated with an account CLI example: .. code-block:: bash salt myminion boto_elb.get_all_elbs region=us-east-1 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: return [e for e in conn.get_all_load_balancers()] except boto.exception.BotoServerError as error: log.warning(error) return [] def list_elbs(region=None, key=None, keyid=None, profile=None): ''' Return names of all load balancers associated with an account CLI example: .. code-block:: bash salt myminion boto_elb.list_elbs region=us-east-1 ''' return [e.name for e in get_all_elbs(region=region, key=key, keyid=keyid, profile=profile)] def get_elb_config(name, region=None, key=None, keyid=None, profile=None): ''' Get an ELB configuration. CLI example: .. code-block:: bash salt myminion boto_elb.exists myelb region=us-east-1 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) retries = 30 while retries: try: lb = conn.get_all_load_balancers(load_balancer_names=[name]) lb = lb[0] ret = {} ret['availability_zones'] = lb.availability_zones listeners = [] for _listener in lb.listeners: listener_dict = {} listener_dict['elb_port'] = _listener.load_balancer_port listener_dict['elb_protocol'] = _listener.protocol listener_dict['instance_port'] = _listener.instance_port listener_dict['instance_protocol'] = _listener.instance_protocol listener_dict['policies'] = _listener.policy_names if _listener.ssl_certificate_id: listener_dict['certificate'] = _listener.ssl_certificate_id listeners.append(listener_dict) ret['listeners'] = listeners backends = [] for _backend in lb.backends: bs_dict = {} bs_dict['instance_port'] = _backend.instance_port bs_dict['policies'] = [p.policy_name for p in _backend.policies] backends.append(bs_dict) ret['backends'] = backends ret['subnets'] = lb.subnets ret['security_groups'] = lb.security_groups ret['scheme'] = lb.scheme ret['dns_name'] = lb.dns_name ret['tags'] = _get_all_tags(conn, name) lb_policy_lists = [ lb.policies.app_cookie_stickiness_policies, lb.policies.lb_cookie_stickiness_policies, lb.policies.other_policies ] policies = [] for policy_list in lb_policy_lists: policies += [p.policy_name for p in policy_list] ret['policies'] = policies return ret except boto.exception.BotoServerError as error: if error.error_code == 'Throttling': log.debug('Throttled by AWS API, will retry in 5 seconds.') time.sleep(5) retries -= 1 continue log.error('Error fetching config for ELB %s: %s', name, error.message) log.error(error) return {} return {} def listener_dict_to_tuple(listener): ''' Convert an ELB listener dict into a listener tuple used by certain parts of the AWS ELB API. CLI example: .. code-block:: bash salt myminion boto_elb.listener_dict_to_tuple '{"elb_port":80,"instance_port":80,"elb_protocol":"HTTP"}' ''' # We define all listeners as complex listeners. if 'instance_protocol' not in listener: instance_protocol = listener['elb_protocol'].upper() else: instance_protocol = listener['instance_protocol'].upper() listener_tuple = [listener['elb_port'], listener['instance_port'], listener['elb_protocol'], instance_protocol] if 'certificate' in listener: listener_tuple.append(listener['certificate']) return tuple(listener_tuple) def create(name, availability_zones, listeners, subnets=None, security_groups=None, scheme='internet-facing', region=None, key=None, keyid=None, profile=None): ''' Create an ELB CLI example to create an ELB: .. code-block:: bash salt myminion boto_elb.create myelb '["us-east-1a", "us-east-1e"]' '{"elb_port": 443, "elb_protocol": "HTTPS", ...}' region=us-east-1 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if exists(name, region, key, keyid, profile): return True if isinstance(availability_zones, six.string_types): availability_zones = salt.utils.json.loads(availability_zones) if isinstance(listeners, six.string_types): listeners = salt.utils.json.loads(listeners) _complex_listeners = [] for listener in listeners: _complex_listeners.append(listener_dict_to_tuple(listener)) try: lb = conn.create_load_balancer(name=name, zones=availability_zones, subnets=subnets, security_groups=security_groups, scheme=scheme, complex_listeners=_complex_listeners) if lb: log.info('Created ELB %s', name) return True else: log.error('Failed to create ELB %s', name) return False except boto.exception.BotoServerError as error: log.error('Failed to create ELB %s: %s: %s', name, error.error_code, error.message, exc_info_on_loglevel=logging.DEBUG) return False def delete(name, region=None, key=None, keyid=None, profile=None): ''' Delete an ELB. CLI example to delete an ELB: .. code-block:: bash salt myminion boto_elb.delete myelb region=us-east-1 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not exists(name, region, key, keyid, profile): return True try: conn.delete_load_balancer(name) log.info('Deleted ELB %s.', name) return True except boto.exception.BotoServerError as error: log.error('Failed to delete ELB %s', name, exc_info_on_loglevel=logging.DEBUG) return False def create_listeners(name, listeners, region=None, key=None, keyid=None, profile=None): ''' Create listeners on an ELB. CLI example: .. code-block:: bash salt myminion boto_elb.create_listeners myelb '[["HTTPS", "HTTP", 443, 80, "arn:aws:iam::11 11111:server-certificate/mycert"]]' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if isinstance(listeners, six.string_types): listeners = salt.utils.json.loads(listeners) _complex_listeners = [] for listener in listeners: _complex_listeners.append(listener_dict_to_tuple(listener)) try: conn.create_load_balancer_listeners(name, [], _complex_listeners) log.info('Created ELB listeners on %s', name) return True except boto.exception.BotoServerError as error: log.error('Failed to create ELB listeners on %s: %s', name, error, exc_info_on_loglevel=logging.DEBUG) return False def delete_listeners(name, ports, region=None, key=None, keyid=None, profile=None): ''' Delete listeners on an ELB. CLI example: .. code-block:: bash salt myminion boto_elb.delete_listeners myelb '[80,443]' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if isinstance(ports, six.string_types): ports = salt.utils.json.loads(ports) try: conn.delete_load_balancer_listeners(name, ports) log.info('Deleted ELB listeners on %s', name) return True except boto.exception.BotoServerError as error: log.error('Failed to delete ELB listeners on %s: %s', name, error, exc_info_on_loglevel=logging.DEBUG) return False def apply_security_groups(name, security_groups, region=None, key=None, keyid=None, profile=None): ''' Apply security groups to ELB. CLI example: .. code-block:: bash salt myminion boto_elb.apply_security_groups myelb '["mysecgroup1"]' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if isinstance(security_groups, six.string_types): security_groups = salt.utils.json.loads(security_groups) try: conn.apply_security_groups_to_lb(name, security_groups) log.info('Applied security_groups on ELB %s', name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to appply security_groups on ELB %s: %s', name, e.message) return False def enable_availability_zones(name, availability_zones, region=None, key=None, keyid=None, profile=None): ''' Enable availability zones for ELB. CLI example: .. code-block:: bash salt myminion boto_elb.enable_availability_zones myelb '["us-east-1a"]' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if isinstance(availability_zones, six.string_types): availability_zones = salt.utils.json.loads(availability_zones) try: conn.enable_availability_zones(name, availability_zones) log.info('Enabled availability_zones on ELB %s', name) return True except boto.exception.BotoServerError as error: log.error('Failed to enable availability_zones on ELB %s: %s', name, error) return False def disable_availability_zones(name, availability_zones, region=None, key=None, keyid=None, profile=None): ''' Disable availability zones for ELB. CLI example: .. code-block:: bash salt myminion boto_elb.disable_availability_zones myelb '["us-east-1a"]' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if isinstance(availability_zones, six.string_types): availability_zones = salt.utils.json.loads(availability_zones) try: conn.disable_availability_zones(name, availability_zones) log.info('Disabled availability_zones on ELB %s', name) return True except boto.exception.BotoServerError as error: log.error('Failed to disable availability_zones on ELB %s: %s', name, error, exc_info_on_loglevel=logging.DEBUG) return False def attach_subnets(name, subnets, region=None, key=None, keyid=None, profile=None): ''' Attach ELB to subnets. CLI example: .. code-block:: bash salt myminion boto_elb.attach_subnets myelb '["mysubnet"]' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if isinstance(subnets, six.string_types): subnets = salt.utils.json.loads(subnets) try: conn.attach_lb_to_subnets(name, subnets) log.info('Attached ELB %s on subnets.', name) return True except boto.exception.BotoServerError as error: log.error('Failed to attach ELB %s on subnets: %s', name, error, exc_info_on_loglevel=logging.DEBUG) return False def detach_subnets(name, subnets, region=None, key=None, keyid=None, profile=None): ''' Detach ELB from subnets. CLI example: .. code-block:: bash salt myminion boto_elb.detach_subnets myelb '["mysubnet"]' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if isinstance(subnets, six.string_types): subnets = salt.utils.json.loads(subnets) try: conn.detach_lb_from_subnets(name, subnets) log.info('Detached ELB %s from subnets.', name) return True except boto.exception.BotoServerError as error: log.error('Failed to detach ELB %s from subnets: %s', name, error, exc_info_on_loglevel=logging.DEBUG) return False def get_attributes(name, region=None, key=None, keyid=None, profile=None): ''' Check to see if attributes are set on an ELB. CLI example: .. code-block:: bash salt myminion boto_elb.get_attributes myelb ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) retries = 30 while retries: try: lbattrs = conn.get_all_lb_attributes(name) ret = odict.OrderedDict() ret['access_log'] = odict.OrderedDict() ret['cross_zone_load_balancing'] = odict.OrderedDict() ret['connection_draining'] = odict.OrderedDict() ret['connecting_settings'] = odict.OrderedDict() al = lbattrs.access_log czlb = lbattrs.cross_zone_load_balancing cd = lbattrs.connection_draining cs = lbattrs.connecting_settings ret['access_log']['enabled'] = al.enabled ret['access_log']['s3_bucket_name'] = al.s3_bucket_name ret['access_log']['s3_bucket_prefix'] = al.s3_bucket_prefix ret['access_log']['emit_interval'] = al.emit_interval ret['cross_zone_load_balancing']['enabled'] = czlb.enabled ret['connection_draining']['enabled'] = cd.enabled ret['connection_draining']['timeout'] = cd.timeout ret['connecting_settings']['idle_timeout'] = cs.idle_timeout return ret except boto.exception.BotoServerError as e: if e.error_code == 'Throttling': log.debug("Throttled by AWS API, will retry in 5 seconds...") time.sleep(5) retries -= 1 continue log.error('ELB %s does not exist: %s', name, e.message) return {} return {} def set_attributes(name, attributes, region=None, key=None, keyid=None, profile=None): ''' Set attributes on an ELB. name (string) Name of the ELB instance to set attributes for attributes A dict of attributes to set. Valid attributes are: access_log (dict) enabled (bool) Enable storage of access logs. s3_bucket_name (string) The name of the S3 bucket to place logs. s3_bucket_prefix (string) Prefix for the log file name. emit_interval (int) Interval for storing logs in S3 in minutes. Valid values are 5 and 60. connection_draining (dict) enabled (bool) Enable connection draining. timeout (int) Maximum allowed time in seconds for sending existing connections to an instance that is deregistering or unhealthy. Default is 300. cross_zone_load_balancing (dict) enabled (bool) Enable cross-zone load balancing. CLI example to set attributes on an ELB: .. code-block:: bash salt myminion boto_elb.set_attributes myelb '{"access_log": {"enabled": "true", "s3_bucket_name": "mybucket", "s3_bucket_prefix": "mylogs/", "emit_interval": "5"}}' region=us-east-1 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) al = attributes.get('access_log', {}) czlb = attributes.get('cross_zone_load_balancing', {}) cd = attributes.get('connection_draining', {}) cs = attributes.get('connecting_settings', {}) if not al and not czlb and not cd and not cs: log.error('No supported attributes for ELB.') return False if al: _al = AccessLogAttribute() _al.enabled = al.get('enabled', False) if not _al.enabled: msg = 'Access log attribute configured, but enabled config missing' log.error(msg) return False _al.s3_bucket_name = al.get('s3_bucket_name', None) _al.s3_bucket_prefix = al.get('s3_bucket_prefix', None) _al.emit_interval = al.get('emit_interval', None) added_attr = conn.modify_lb_attribute(name, 'accessLog', _al) if added_attr: log.info('Added access_log attribute to %s elb.', name) else: log.error('Failed to add access_log attribute to %s elb.', name) return False if czlb: _czlb = CrossZoneLoadBalancingAttribute() _czlb.enabled = czlb['enabled'] added_attr = conn.modify_lb_attribute(name, 'crossZoneLoadBalancing', _czlb.enabled) if added_attr: log.info('Added cross_zone_load_balancing attribute to %s elb.', name) else: log.error('Failed to add cross_zone_load_balancing attribute.') return False if cd: _cd = ConnectionDrainingAttribute() _cd.enabled = cd['enabled'] _cd.timeout = cd.get('timeout', 300) added_attr = conn.modify_lb_attribute(name, 'connectionDraining', _cd) if added_attr: log.info('Added connection_draining attribute to %s elb.', name) else: log.error('Failed to add connection_draining attribute.') return False if cs: _cs = ConnectionSettingAttribute() _cs.idle_timeout = cs.get('idle_timeout', 60) added_attr = conn.modify_lb_attribute(name, 'connectingSettings', _cs) if added_attr: log.info('Added connecting_settings attribute to %s elb.', name) else: log.error('Failed to add connecting_settings attribute.') return False return True def get_health_check(name, region=None, key=None, keyid=None, profile=None): ''' Get the health check configured for this ELB. CLI example: .. code-block:: bash salt myminion boto_elb.get_health_check myelb ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) retries = 30 while True: try: lb = conn.get_all_load_balancers(load_balancer_names=[name]) lb = lb[0] ret = odict.OrderedDict() hc = lb.health_check ret['interval'] = hc.interval ret['target'] = hc.target ret['healthy_threshold'] = hc.healthy_threshold ret['timeout'] = hc.timeout ret['unhealthy_threshold'] = hc.unhealthy_threshold return ret except boto.exception.BotoServerError as e: if retries and e.code == 'Throttling': log.debug('Throttled by AWS API, will retry in 5 seconds.') time.sleep(5) retries -= 1 continue log.error('ELB %s not found.', name, exc_info_on_logleve=logging.DEBUG) return {} def set_health_check(name, health_check, region=None, key=None, keyid=None, profile=None): ''' Set attributes on an ELB. CLI example to set attributes on an ELB: .. code-block:: bash salt myminion boto_elb.set_health_check myelb '{"target": "HTTP:80/"}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) retries = 30 hc = HealthCheck(**health_check) while True: try: conn.configure_health_check(name, hc) log.info('Configured health check on ELB %s', name) return True except boto.exception.BotoServerError as error: if retries and e.code == 'Throttling': log.debug('Throttled by AWS API, will retry in 5 seconds.') time.sleep(5) retries -= 1 continue log.exception('Failed to configure health check on ELB %s', name) return False def register_instances(name, instances, region=None, key=None, keyid=None, profile=None): ''' Register instances with an ELB. Instances is either a string instance id or a list of string instance id's. Returns: - ``True``: instance(s) registered successfully - ``False``: instance(s) failed to be registered CLI example: .. code-block:: bash salt myminion boto_elb.register_instances myelb instance_id salt myminion boto_elb.register_instances myelb "[instance_id,instance_id]" ''' # convert instances to list type, enabling consistent use of instances # variable throughout the register_instances method if isinstance(instances, six.string_types) or isinstance(instances, six.text_type): instances = [instances] conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: registered_instances = conn.register_instances(name, instances) except boto.exception.BotoServerError as error: log.warning(error) return False registered_instance_ids = [instance.id for instance in registered_instances] # register_failues is a set that will contain any instances that were not # able to be registered with the given ELB register_failures = set(instances).difference(set(registered_instance_ids)) if register_failures: log.warning('Instance(s): %s not registered with ELB %s.', list(register_failures), name) register_result = False else: register_result = True return register_result def deregister_instances(name, instances, region=None, key=None, keyid=None, profile=None): ''' Deregister instances with an ELB. Instances is either a string instance id or a list of string instance id's. Returns: - ``True``: instance(s) deregistered successfully - ``False``: instance(s) failed to be deregistered - ``None``: instance(s) not valid or not registered, no action taken CLI example: .. code-block:: bash salt myminion boto_elb.deregister_instances myelb instance_id salt myminion boto_elb.deregister_instances myelb "[instance_id, instance_id]" ''' # convert instances to list type, enabling consistent use of instances # variable throughout the deregister_instances method if isinstance(instances, six.string_types) or isinstance(instances, six.text_type): instances = [instances] conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: registered_instances = conn.deregister_instances(name, instances) except boto.exception.BotoServerError as error: # if the instance(s) given as an argument are not members of the ELB # boto returns error.error_code == 'InvalidInstance' # deregister_instances returns "None" because the instances are # effectively deregistered from ELB if error.error_code == 'InvalidInstance': log.warning( 'One or more of instance(s) %s are not part of ELB %s. ' 'deregister_instances not performed.', instances, name ) return None else: log.warning(error) return False registered_instance_ids = [instance.id for instance in registered_instances] # deregister_failures is a set that will contain any instances that were # unable to be deregistered from the given ELB deregister_failures = set(instances).intersection(set(registered_instance_ids)) if deregister_failures: log.warning( 'Instance(s): %s not deregistered from ELB %s.', list(deregister_failures), name ) deregister_result = False else: deregister_result = True return deregister_result def set_instances(name, instances, test=False, region=None, key=None, keyid=None, profile=None): ''' Set the instances assigned to an ELB to exactly the list given CLI example: .. code-block:: bash salt myminion boto_elb.set_instances myelb region=us-east-1 instances="[instance_id,instance_id]" ''' ret = True current = set([i['instance_id'] for i in get_instance_health(name, region, key, keyid, profile)]) desired = set(instances) add = desired - current remove = current - desired if test: return bool(add or remove) if remove: if deregister_instances(name, list(remove), region, key, keyid, profile) is False: ret = False if add: if register_instances(name, list(add), region, key, keyid, profile) is False: ret = False return ret def create_policy(name, policy_name, policy_type, policy, region=None, key=None, keyid=None, profile=None): ''' Create an ELB policy. .. versionadded:: 2016.3.0 CLI example: .. code-block:: bash salt myminion boto_elb.create_policy myelb mypolicy LBCookieStickinessPolicyType '{"CookieExpirationPeriod": 3600}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not exists(name, region, key, keyid, profile): return False try: success = conn.create_lb_policy(name, policy_name, policy_type, policy) if success: log.info('Created policy %s on ELB %s', policy_name, name) return True else: log.error('Failed to create policy %s on ELB %s', policy_name, name) return False except boto.exception.BotoServerError as e: log.error('Failed to create policy %s on ELB %s: %s', policy_name, name, e.message, exc_info_on_loglevel=logging.DEBUG) return False def delete_policy(name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Delete an ELB policy. .. versionadded:: 2016.3.0 CLI example: .. code-block:: bash salt myminion boto_elb.delete_policy myelb mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not exists(name, region, key, keyid, profile): return True try: conn.delete_lb_policy(name, policy_name) log.info('Deleted policy %s on ELB %s', policy_name, name) return True except boto.exception.BotoServerError as e: log.error('Failed to delete policy %s on ELB %s: %s', policy_name, name, e.message, exc_info_on_loglevel=logging.DEBUG) return False def set_listener_policy(name, port, policies=None, region=None, key=None, keyid=None, profile=None): ''' Set the policies of an ELB listener. .. versionadded:: 2016.3.0 CLI example: .. code-block:: Bash salt myminion boto_elb.set_listener_policy myelb 443 "[policy1,policy2]" ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not exists(name, region, key, keyid, profile): return True if policies is None: policies = [] try: conn.set_lb_policies_of_listener(name, port, policies) log.info('Set policies %s on ELB %s listener %s', policies, name, port) except boto.exception.BotoServerError as e: log.info('Failed to set policy %s on ELB %s listener %s: %s', policies, name, port, e.message, exc_info_on_loglevel=logging.DEBUG) return False return True def set_backend_policy(name, port, policies=None, region=None, key=None, keyid=None, profile=None): ''' Set the policies of an ELB backend server. CLI example: salt myminion boto_elb.set_backend_policy myelb 443 "[policy1,policy2]" ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not exists(name, region, key, keyid, profile): return True if policies is None: policies = [] try: conn.set_lb_policies_of_backend_server(name, port, policies) log.info('Set policies %s on ELB %s backend server %s', policies, name, port) except boto.exception.BotoServerError as e: log.info('Failed to set policy %s on ELB %s backend server %s: %s', policies, name, port, e.message, exc_info_on_loglevel=logging.DEBUG) return False return True def set_tags(name, tags, region=None, key=None, keyid=None, profile=None): ''' Add the tags on an ELB .. versionadded:: 2016.3.0 name name of the ELB tags dict of name/value pair tags CLI Example: .. code-block:: bash salt myminion boto_elb.set_tags my-elb-name "{'Tag1': 'Value', 'Tag2': 'Another Value'}" ''' if exists(name, region, key, keyid, profile): conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) ret = _add_tags(conn, name, tags) return ret else: return False def delete_tags(name, tags, region=None, key=None, keyid=None, profile=None): ''' Add the tags on an ELB name name of the ELB tags list of tags to remove CLI Example: .. code-block:: bash salt myminion boto_elb.delete_tags my-elb-name ['TagToRemove1', 'TagToRemove2'] ''' if exists(name, region, key, keyid, profile): conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) ret = _remove_tags(conn, name, tags) return ret else: return False def _build_tag_param_list(params, tags): ''' helper function to build a tag parameter list to send ''' keys = sorted(tags.keys()) i = 1 for key in keys: value = tags[key] params['Tags.member.{0}.Key'.format(i)] = key if value is not None: params['Tags.member.{0}.Value'.format(i)] = value i += 1 def _get_all_tags(conn, load_balancer_names=None): ''' Retrieve all the metadata tags associated with your ELB(s). :type load_balancer_names: list :param load_balancer_names: An optional list of load balancer names. :rtype: list :return: A list of :class:`boto.ec2.elb.tag.Tag` objects ''' params = {} if load_balancer_names: conn.build_list_params(params, load_balancer_names, 'LoadBalancerNames.member.%d') tags = conn.get_object( 'DescribeTags', params, __utils__['boto_elb_tag.get_tag_descriptions'](), verb='POST' ) if tags[load_balancer_names]: return tags[load_balancer_names] else: return None def _add_tags(conn, load_balancer_names, tags): ''' Create new metadata tags for the specified resource ids. :type load_balancer_names: list :param load_balancer_names: A list of load balancer names. :type tags: dict :param tags: A dictionary containing the name/value pairs. If you want to create only a tag name, the value for that tag should be the empty string (e.g. ''). ''' params = {} conn.build_list_params(params, load_balancer_names, 'LoadBalancerNames.member.%d') _build_tag_param_list(params, tags) return conn.get_status('AddTags', params, verb='POST') def _remove_tags(conn, load_balancer_names, tags): ''' Delete metadata tags for the specified resource ids. :type load_balancer_names: list :param load_balancer_names: A list of load balancer names. :type tags: list :param tags: A list containing just tag names for the tags to be deleted. ''' params = {} conn.build_list_params(params, load_balancer_names, 'LoadBalancerNames.member.%d') conn.build_list_params(params, tags, 'Tags.member.%d.Key') return conn.get_status('RemoveTags', params, verb='POST')
saltstack/salt
salt/modules/boto_elb.py
create_policy
python
def create_policy(name, policy_name, policy_type, policy, region=None, key=None, keyid=None, profile=None): ''' Create an ELB policy. .. versionadded:: 2016.3.0 CLI example: .. code-block:: bash salt myminion boto_elb.create_policy myelb mypolicy LBCookieStickinessPolicyType '{"CookieExpirationPeriod": 3600}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not exists(name, region, key, keyid, profile): return False try: success = conn.create_lb_policy(name, policy_name, policy_type, policy) if success: log.info('Created policy %s on ELB %s', policy_name, name) return True else: log.error('Failed to create policy %s on ELB %s', policy_name, name) return False except boto.exception.BotoServerError as e: log.error('Failed to create policy %s on ELB %s: %s', policy_name, name, e.message, exc_info_on_loglevel=logging.DEBUG) return False
Create an ELB policy. .. versionadded:: 2016.3.0 CLI example: .. code-block:: bash salt myminion boto_elb.create_policy myelb mypolicy LBCookieStickinessPolicyType '{"CookieExpirationPeriod": 3600}'
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_elb.py#L847-L876
[ "def exists(name, region=None, key=None, keyid=None, profile=None):\n '''\n Check to see if an ELB exists.\n\n CLI example:\n\n .. code-block:: bash\n\n salt myminion boto_elb.exists myelb region=us-east-1\n '''\n conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)\n\n try:\n elb = conn.get_all_load_balancers(load_balancer_names=[name])\n if elb:\n return True\n else:\n log.debug('The load balancer does not exist in region %s', region)\n return False\n except boto.exception.BotoServerError as error:\n log.warning(error)\n return False\n" ]
# -*- coding: utf-8 -*- ''' Connection module for Amazon ELB .. versionadded:: 2014.7.0 :configuration: This module accepts explicit elb credentials but can also utilize IAM roles assigned to the instance through Instance Profiles. Dynamic credentials are then automatically obtained from AWS API and no further configuration is necessary. More Information available at: .. code-block:: text http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/iam-roles-for-amazon-ec2.html If IAM roles are not used you need to specify them either in a pillar or in the minion's config file: .. code-block:: yaml elb.keyid: GKTADJGHEIQSXMKKRBJ08H elb.key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs A region may also be specified in the configuration: .. code-block:: yaml elb.region: us-east-1 If a region is not specified, the default is us-east-1. It's also possible to specify key, keyid and region via a profile, either as a passed in dict, or as a string to pull from pillars or minion config: .. code-block:: yaml myprofile: keyid: GKTADJGHEIQSXMKKRBJ08H key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs region: us-east-1 :depends: boto >= 2.33.0 ''' # keep lint from choking on _get_conn and _cache_id # pylint: disable=E0602 from __future__ import absolute_import, print_function, unicode_literals # Import Python libs import logging import time log = logging.getLogger(__name__) # Import Salt libs import salt.utils.json import salt.utils.odict as odict import salt.utils.versions # Import third party libs from salt.ext import six try: import boto import boto.ec2 # pylint: enable=unused-import from boto.ec2.elb import HealthCheck from boto.ec2.elb.attributes import AccessLogAttribute from boto.ec2.elb.attributes import ConnectionDrainingAttribute from boto.ec2.elb.attributes import ConnectionSettingAttribute from boto.ec2.elb.attributes import CrossZoneLoadBalancingAttribute logging.getLogger('boto').setLevel(logging.CRITICAL) HAS_BOTO = True except ImportError: HAS_BOTO = False def __virtual__(): ''' Only load if boto libraries exist. ''' # connection settings were added in 2.33.0 has_boto_reqs = salt.utils.versions.check_boto_reqs( boto_ver='2.33.0', check_boto3=False ) if has_boto_reqs is True: __utils__['boto.assign_funcs'](__name__, 'elb', module='ec2.elb', pack=__salt__) return has_boto_reqs def exists(name, region=None, key=None, keyid=None, profile=None): ''' Check to see if an ELB exists. CLI example: .. code-block:: bash salt myminion boto_elb.exists myelb region=us-east-1 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: elb = conn.get_all_load_balancers(load_balancer_names=[name]) if elb: return True else: log.debug('The load balancer does not exist in region %s', region) return False except boto.exception.BotoServerError as error: log.warning(error) return False def get_all_elbs(region=None, key=None, keyid=None, profile=None): ''' Return all load balancers associated with an account CLI example: .. code-block:: bash salt myminion boto_elb.get_all_elbs region=us-east-1 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: return [e for e in conn.get_all_load_balancers()] except boto.exception.BotoServerError as error: log.warning(error) return [] def list_elbs(region=None, key=None, keyid=None, profile=None): ''' Return names of all load balancers associated with an account CLI example: .. code-block:: bash salt myminion boto_elb.list_elbs region=us-east-1 ''' return [e.name for e in get_all_elbs(region=region, key=key, keyid=keyid, profile=profile)] def get_elb_config(name, region=None, key=None, keyid=None, profile=None): ''' Get an ELB configuration. CLI example: .. code-block:: bash salt myminion boto_elb.exists myelb region=us-east-1 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) retries = 30 while retries: try: lb = conn.get_all_load_balancers(load_balancer_names=[name]) lb = lb[0] ret = {} ret['availability_zones'] = lb.availability_zones listeners = [] for _listener in lb.listeners: listener_dict = {} listener_dict['elb_port'] = _listener.load_balancer_port listener_dict['elb_protocol'] = _listener.protocol listener_dict['instance_port'] = _listener.instance_port listener_dict['instance_protocol'] = _listener.instance_protocol listener_dict['policies'] = _listener.policy_names if _listener.ssl_certificate_id: listener_dict['certificate'] = _listener.ssl_certificate_id listeners.append(listener_dict) ret['listeners'] = listeners backends = [] for _backend in lb.backends: bs_dict = {} bs_dict['instance_port'] = _backend.instance_port bs_dict['policies'] = [p.policy_name for p in _backend.policies] backends.append(bs_dict) ret['backends'] = backends ret['subnets'] = lb.subnets ret['security_groups'] = lb.security_groups ret['scheme'] = lb.scheme ret['dns_name'] = lb.dns_name ret['tags'] = _get_all_tags(conn, name) lb_policy_lists = [ lb.policies.app_cookie_stickiness_policies, lb.policies.lb_cookie_stickiness_policies, lb.policies.other_policies ] policies = [] for policy_list in lb_policy_lists: policies += [p.policy_name for p in policy_list] ret['policies'] = policies return ret except boto.exception.BotoServerError as error: if error.error_code == 'Throttling': log.debug('Throttled by AWS API, will retry in 5 seconds.') time.sleep(5) retries -= 1 continue log.error('Error fetching config for ELB %s: %s', name, error.message) log.error(error) return {} return {} def listener_dict_to_tuple(listener): ''' Convert an ELB listener dict into a listener tuple used by certain parts of the AWS ELB API. CLI example: .. code-block:: bash salt myminion boto_elb.listener_dict_to_tuple '{"elb_port":80,"instance_port":80,"elb_protocol":"HTTP"}' ''' # We define all listeners as complex listeners. if 'instance_protocol' not in listener: instance_protocol = listener['elb_protocol'].upper() else: instance_protocol = listener['instance_protocol'].upper() listener_tuple = [listener['elb_port'], listener['instance_port'], listener['elb_protocol'], instance_protocol] if 'certificate' in listener: listener_tuple.append(listener['certificate']) return tuple(listener_tuple) def create(name, availability_zones, listeners, subnets=None, security_groups=None, scheme='internet-facing', region=None, key=None, keyid=None, profile=None): ''' Create an ELB CLI example to create an ELB: .. code-block:: bash salt myminion boto_elb.create myelb '["us-east-1a", "us-east-1e"]' '{"elb_port": 443, "elb_protocol": "HTTPS", ...}' region=us-east-1 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if exists(name, region, key, keyid, profile): return True if isinstance(availability_zones, six.string_types): availability_zones = salt.utils.json.loads(availability_zones) if isinstance(listeners, six.string_types): listeners = salt.utils.json.loads(listeners) _complex_listeners = [] for listener in listeners: _complex_listeners.append(listener_dict_to_tuple(listener)) try: lb = conn.create_load_balancer(name=name, zones=availability_zones, subnets=subnets, security_groups=security_groups, scheme=scheme, complex_listeners=_complex_listeners) if lb: log.info('Created ELB %s', name) return True else: log.error('Failed to create ELB %s', name) return False except boto.exception.BotoServerError as error: log.error('Failed to create ELB %s: %s: %s', name, error.error_code, error.message, exc_info_on_loglevel=logging.DEBUG) return False def delete(name, region=None, key=None, keyid=None, profile=None): ''' Delete an ELB. CLI example to delete an ELB: .. code-block:: bash salt myminion boto_elb.delete myelb region=us-east-1 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not exists(name, region, key, keyid, profile): return True try: conn.delete_load_balancer(name) log.info('Deleted ELB %s.', name) return True except boto.exception.BotoServerError as error: log.error('Failed to delete ELB %s', name, exc_info_on_loglevel=logging.DEBUG) return False def create_listeners(name, listeners, region=None, key=None, keyid=None, profile=None): ''' Create listeners on an ELB. CLI example: .. code-block:: bash salt myminion boto_elb.create_listeners myelb '[["HTTPS", "HTTP", 443, 80, "arn:aws:iam::11 11111:server-certificate/mycert"]]' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if isinstance(listeners, six.string_types): listeners = salt.utils.json.loads(listeners) _complex_listeners = [] for listener in listeners: _complex_listeners.append(listener_dict_to_tuple(listener)) try: conn.create_load_balancer_listeners(name, [], _complex_listeners) log.info('Created ELB listeners on %s', name) return True except boto.exception.BotoServerError as error: log.error('Failed to create ELB listeners on %s: %s', name, error, exc_info_on_loglevel=logging.DEBUG) return False def delete_listeners(name, ports, region=None, key=None, keyid=None, profile=None): ''' Delete listeners on an ELB. CLI example: .. code-block:: bash salt myminion boto_elb.delete_listeners myelb '[80,443]' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if isinstance(ports, six.string_types): ports = salt.utils.json.loads(ports) try: conn.delete_load_balancer_listeners(name, ports) log.info('Deleted ELB listeners on %s', name) return True except boto.exception.BotoServerError as error: log.error('Failed to delete ELB listeners on %s: %s', name, error, exc_info_on_loglevel=logging.DEBUG) return False def apply_security_groups(name, security_groups, region=None, key=None, keyid=None, profile=None): ''' Apply security groups to ELB. CLI example: .. code-block:: bash salt myminion boto_elb.apply_security_groups myelb '["mysecgroup1"]' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if isinstance(security_groups, six.string_types): security_groups = salt.utils.json.loads(security_groups) try: conn.apply_security_groups_to_lb(name, security_groups) log.info('Applied security_groups on ELB %s', name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to appply security_groups on ELB %s: %s', name, e.message) return False def enable_availability_zones(name, availability_zones, region=None, key=None, keyid=None, profile=None): ''' Enable availability zones for ELB. CLI example: .. code-block:: bash salt myminion boto_elb.enable_availability_zones myelb '["us-east-1a"]' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if isinstance(availability_zones, six.string_types): availability_zones = salt.utils.json.loads(availability_zones) try: conn.enable_availability_zones(name, availability_zones) log.info('Enabled availability_zones on ELB %s', name) return True except boto.exception.BotoServerError as error: log.error('Failed to enable availability_zones on ELB %s: %s', name, error) return False def disable_availability_zones(name, availability_zones, region=None, key=None, keyid=None, profile=None): ''' Disable availability zones for ELB. CLI example: .. code-block:: bash salt myminion boto_elb.disable_availability_zones myelb '["us-east-1a"]' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if isinstance(availability_zones, six.string_types): availability_zones = salt.utils.json.loads(availability_zones) try: conn.disable_availability_zones(name, availability_zones) log.info('Disabled availability_zones on ELB %s', name) return True except boto.exception.BotoServerError as error: log.error('Failed to disable availability_zones on ELB %s: %s', name, error, exc_info_on_loglevel=logging.DEBUG) return False def attach_subnets(name, subnets, region=None, key=None, keyid=None, profile=None): ''' Attach ELB to subnets. CLI example: .. code-block:: bash salt myminion boto_elb.attach_subnets myelb '["mysubnet"]' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if isinstance(subnets, six.string_types): subnets = salt.utils.json.loads(subnets) try: conn.attach_lb_to_subnets(name, subnets) log.info('Attached ELB %s on subnets.', name) return True except boto.exception.BotoServerError as error: log.error('Failed to attach ELB %s on subnets: %s', name, error, exc_info_on_loglevel=logging.DEBUG) return False def detach_subnets(name, subnets, region=None, key=None, keyid=None, profile=None): ''' Detach ELB from subnets. CLI example: .. code-block:: bash salt myminion boto_elb.detach_subnets myelb '["mysubnet"]' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if isinstance(subnets, six.string_types): subnets = salt.utils.json.loads(subnets) try: conn.detach_lb_from_subnets(name, subnets) log.info('Detached ELB %s from subnets.', name) return True except boto.exception.BotoServerError as error: log.error('Failed to detach ELB %s from subnets: %s', name, error, exc_info_on_loglevel=logging.DEBUG) return False def get_attributes(name, region=None, key=None, keyid=None, profile=None): ''' Check to see if attributes are set on an ELB. CLI example: .. code-block:: bash salt myminion boto_elb.get_attributes myelb ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) retries = 30 while retries: try: lbattrs = conn.get_all_lb_attributes(name) ret = odict.OrderedDict() ret['access_log'] = odict.OrderedDict() ret['cross_zone_load_balancing'] = odict.OrderedDict() ret['connection_draining'] = odict.OrderedDict() ret['connecting_settings'] = odict.OrderedDict() al = lbattrs.access_log czlb = lbattrs.cross_zone_load_balancing cd = lbattrs.connection_draining cs = lbattrs.connecting_settings ret['access_log']['enabled'] = al.enabled ret['access_log']['s3_bucket_name'] = al.s3_bucket_name ret['access_log']['s3_bucket_prefix'] = al.s3_bucket_prefix ret['access_log']['emit_interval'] = al.emit_interval ret['cross_zone_load_balancing']['enabled'] = czlb.enabled ret['connection_draining']['enabled'] = cd.enabled ret['connection_draining']['timeout'] = cd.timeout ret['connecting_settings']['idle_timeout'] = cs.idle_timeout return ret except boto.exception.BotoServerError as e: if e.error_code == 'Throttling': log.debug("Throttled by AWS API, will retry in 5 seconds...") time.sleep(5) retries -= 1 continue log.error('ELB %s does not exist: %s', name, e.message) return {} return {} def set_attributes(name, attributes, region=None, key=None, keyid=None, profile=None): ''' Set attributes on an ELB. name (string) Name of the ELB instance to set attributes for attributes A dict of attributes to set. Valid attributes are: access_log (dict) enabled (bool) Enable storage of access logs. s3_bucket_name (string) The name of the S3 bucket to place logs. s3_bucket_prefix (string) Prefix for the log file name. emit_interval (int) Interval for storing logs in S3 in minutes. Valid values are 5 and 60. connection_draining (dict) enabled (bool) Enable connection draining. timeout (int) Maximum allowed time in seconds for sending existing connections to an instance that is deregistering or unhealthy. Default is 300. cross_zone_load_balancing (dict) enabled (bool) Enable cross-zone load balancing. CLI example to set attributes on an ELB: .. code-block:: bash salt myminion boto_elb.set_attributes myelb '{"access_log": {"enabled": "true", "s3_bucket_name": "mybucket", "s3_bucket_prefix": "mylogs/", "emit_interval": "5"}}' region=us-east-1 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) al = attributes.get('access_log', {}) czlb = attributes.get('cross_zone_load_balancing', {}) cd = attributes.get('connection_draining', {}) cs = attributes.get('connecting_settings', {}) if not al and not czlb and not cd and not cs: log.error('No supported attributes for ELB.') return False if al: _al = AccessLogAttribute() _al.enabled = al.get('enabled', False) if not _al.enabled: msg = 'Access log attribute configured, but enabled config missing' log.error(msg) return False _al.s3_bucket_name = al.get('s3_bucket_name', None) _al.s3_bucket_prefix = al.get('s3_bucket_prefix', None) _al.emit_interval = al.get('emit_interval', None) added_attr = conn.modify_lb_attribute(name, 'accessLog', _al) if added_attr: log.info('Added access_log attribute to %s elb.', name) else: log.error('Failed to add access_log attribute to %s elb.', name) return False if czlb: _czlb = CrossZoneLoadBalancingAttribute() _czlb.enabled = czlb['enabled'] added_attr = conn.modify_lb_attribute(name, 'crossZoneLoadBalancing', _czlb.enabled) if added_attr: log.info('Added cross_zone_load_balancing attribute to %s elb.', name) else: log.error('Failed to add cross_zone_load_balancing attribute.') return False if cd: _cd = ConnectionDrainingAttribute() _cd.enabled = cd['enabled'] _cd.timeout = cd.get('timeout', 300) added_attr = conn.modify_lb_attribute(name, 'connectionDraining', _cd) if added_attr: log.info('Added connection_draining attribute to %s elb.', name) else: log.error('Failed to add connection_draining attribute.') return False if cs: _cs = ConnectionSettingAttribute() _cs.idle_timeout = cs.get('idle_timeout', 60) added_attr = conn.modify_lb_attribute(name, 'connectingSettings', _cs) if added_attr: log.info('Added connecting_settings attribute to %s elb.', name) else: log.error('Failed to add connecting_settings attribute.') return False return True def get_health_check(name, region=None, key=None, keyid=None, profile=None): ''' Get the health check configured for this ELB. CLI example: .. code-block:: bash salt myminion boto_elb.get_health_check myelb ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) retries = 30 while True: try: lb = conn.get_all_load_balancers(load_balancer_names=[name]) lb = lb[0] ret = odict.OrderedDict() hc = lb.health_check ret['interval'] = hc.interval ret['target'] = hc.target ret['healthy_threshold'] = hc.healthy_threshold ret['timeout'] = hc.timeout ret['unhealthy_threshold'] = hc.unhealthy_threshold return ret except boto.exception.BotoServerError as e: if retries and e.code == 'Throttling': log.debug('Throttled by AWS API, will retry in 5 seconds.') time.sleep(5) retries -= 1 continue log.error('ELB %s not found.', name, exc_info_on_logleve=logging.DEBUG) return {} def set_health_check(name, health_check, region=None, key=None, keyid=None, profile=None): ''' Set attributes on an ELB. CLI example to set attributes on an ELB: .. code-block:: bash salt myminion boto_elb.set_health_check myelb '{"target": "HTTP:80/"}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) retries = 30 hc = HealthCheck(**health_check) while True: try: conn.configure_health_check(name, hc) log.info('Configured health check on ELB %s', name) return True except boto.exception.BotoServerError as error: if retries and e.code == 'Throttling': log.debug('Throttled by AWS API, will retry in 5 seconds.') time.sleep(5) retries -= 1 continue log.exception('Failed to configure health check on ELB %s', name) return False def register_instances(name, instances, region=None, key=None, keyid=None, profile=None): ''' Register instances with an ELB. Instances is either a string instance id or a list of string instance id's. Returns: - ``True``: instance(s) registered successfully - ``False``: instance(s) failed to be registered CLI example: .. code-block:: bash salt myminion boto_elb.register_instances myelb instance_id salt myminion boto_elb.register_instances myelb "[instance_id,instance_id]" ''' # convert instances to list type, enabling consistent use of instances # variable throughout the register_instances method if isinstance(instances, six.string_types) or isinstance(instances, six.text_type): instances = [instances] conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: registered_instances = conn.register_instances(name, instances) except boto.exception.BotoServerError as error: log.warning(error) return False registered_instance_ids = [instance.id for instance in registered_instances] # register_failues is a set that will contain any instances that were not # able to be registered with the given ELB register_failures = set(instances).difference(set(registered_instance_ids)) if register_failures: log.warning('Instance(s): %s not registered with ELB %s.', list(register_failures), name) register_result = False else: register_result = True return register_result def deregister_instances(name, instances, region=None, key=None, keyid=None, profile=None): ''' Deregister instances with an ELB. Instances is either a string instance id or a list of string instance id's. Returns: - ``True``: instance(s) deregistered successfully - ``False``: instance(s) failed to be deregistered - ``None``: instance(s) not valid or not registered, no action taken CLI example: .. code-block:: bash salt myminion boto_elb.deregister_instances myelb instance_id salt myminion boto_elb.deregister_instances myelb "[instance_id, instance_id]" ''' # convert instances to list type, enabling consistent use of instances # variable throughout the deregister_instances method if isinstance(instances, six.string_types) or isinstance(instances, six.text_type): instances = [instances] conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: registered_instances = conn.deregister_instances(name, instances) except boto.exception.BotoServerError as error: # if the instance(s) given as an argument are not members of the ELB # boto returns error.error_code == 'InvalidInstance' # deregister_instances returns "None" because the instances are # effectively deregistered from ELB if error.error_code == 'InvalidInstance': log.warning( 'One or more of instance(s) %s are not part of ELB %s. ' 'deregister_instances not performed.', instances, name ) return None else: log.warning(error) return False registered_instance_ids = [instance.id for instance in registered_instances] # deregister_failures is a set that will contain any instances that were # unable to be deregistered from the given ELB deregister_failures = set(instances).intersection(set(registered_instance_ids)) if deregister_failures: log.warning( 'Instance(s): %s not deregistered from ELB %s.', list(deregister_failures), name ) deregister_result = False else: deregister_result = True return deregister_result def set_instances(name, instances, test=False, region=None, key=None, keyid=None, profile=None): ''' Set the instances assigned to an ELB to exactly the list given CLI example: .. code-block:: bash salt myminion boto_elb.set_instances myelb region=us-east-1 instances="[instance_id,instance_id]" ''' ret = True current = set([i['instance_id'] for i in get_instance_health(name, region, key, keyid, profile)]) desired = set(instances) add = desired - current remove = current - desired if test: return bool(add or remove) if remove: if deregister_instances(name, list(remove), region, key, keyid, profile) is False: ret = False if add: if register_instances(name, list(add), region, key, keyid, profile) is False: ret = False return ret def get_instance_health(name, region=None, key=None, keyid=None, profile=None, instances=None): ''' Get a list of instances and their health state CLI example: .. code-block:: bash salt myminion boto_elb.get_instance_health myelb salt myminion boto_elb.get_instance_health myelb region=us-east-1 instances="[instance_id,instance_id]" ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: instance_states = conn.describe_instance_health(name, instances) ret = [] for _instance in instance_states: ret.append({'instance_id': _instance.instance_id, 'description': _instance.description, 'state': _instance.state, 'reason_code': _instance.reason_code }) return ret except boto.exception.BotoServerError as error: log.debug(error) return [] def delete_policy(name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Delete an ELB policy. .. versionadded:: 2016.3.0 CLI example: .. code-block:: bash salt myminion boto_elb.delete_policy myelb mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not exists(name, region, key, keyid, profile): return True try: conn.delete_lb_policy(name, policy_name) log.info('Deleted policy %s on ELB %s', policy_name, name) return True except boto.exception.BotoServerError as e: log.error('Failed to delete policy %s on ELB %s: %s', policy_name, name, e.message, exc_info_on_loglevel=logging.DEBUG) return False def set_listener_policy(name, port, policies=None, region=None, key=None, keyid=None, profile=None): ''' Set the policies of an ELB listener. .. versionadded:: 2016.3.0 CLI example: .. code-block:: Bash salt myminion boto_elb.set_listener_policy myelb 443 "[policy1,policy2]" ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not exists(name, region, key, keyid, profile): return True if policies is None: policies = [] try: conn.set_lb_policies_of_listener(name, port, policies) log.info('Set policies %s on ELB %s listener %s', policies, name, port) except boto.exception.BotoServerError as e: log.info('Failed to set policy %s on ELB %s listener %s: %s', policies, name, port, e.message, exc_info_on_loglevel=logging.DEBUG) return False return True def set_backend_policy(name, port, policies=None, region=None, key=None, keyid=None, profile=None): ''' Set the policies of an ELB backend server. CLI example: salt myminion boto_elb.set_backend_policy myelb 443 "[policy1,policy2]" ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not exists(name, region, key, keyid, profile): return True if policies is None: policies = [] try: conn.set_lb_policies_of_backend_server(name, port, policies) log.info('Set policies %s on ELB %s backend server %s', policies, name, port) except boto.exception.BotoServerError as e: log.info('Failed to set policy %s on ELB %s backend server %s: %s', policies, name, port, e.message, exc_info_on_loglevel=logging.DEBUG) return False return True def set_tags(name, tags, region=None, key=None, keyid=None, profile=None): ''' Add the tags on an ELB .. versionadded:: 2016.3.0 name name of the ELB tags dict of name/value pair tags CLI Example: .. code-block:: bash salt myminion boto_elb.set_tags my-elb-name "{'Tag1': 'Value', 'Tag2': 'Another Value'}" ''' if exists(name, region, key, keyid, profile): conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) ret = _add_tags(conn, name, tags) return ret else: return False def delete_tags(name, tags, region=None, key=None, keyid=None, profile=None): ''' Add the tags on an ELB name name of the ELB tags list of tags to remove CLI Example: .. code-block:: bash salt myminion boto_elb.delete_tags my-elb-name ['TagToRemove1', 'TagToRemove2'] ''' if exists(name, region, key, keyid, profile): conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) ret = _remove_tags(conn, name, tags) return ret else: return False def _build_tag_param_list(params, tags): ''' helper function to build a tag parameter list to send ''' keys = sorted(tags.keys()) i = 1 for key in keys: value = tags[key] params['Tags.member.{0}.Key'.format(i)] = key if value is not None: params['Tags.member.{0}.Value'.format(i)] = value i += 1 def _get_all_tags(conn, load_balancer_names=None): ''' Retrieve all the metadata tags associated with your ELB(s). :type load_balancer_names: list :param load_balancer_names: An optional list of load balancer names. :rtype: list :return: A list of :class:`boto.ec2.elb.tag.Tag` objects ''' params = {} if load_balancer_names: conn.build_list_params(params, load_balancer_names, 'LoadBalancerNames.member.%d') tags = conn.get_object( 'DescribeTags', params, __utils__['boto_elb_tag.get_tag_descriptions'](), verb='POST' ) if tags[load_balancer_names]: return tags[load_balancer_names] else: return None def _add_tags(conn, load_balancer_names, tags): ''' Create new metadata tags for the specified resource ids. :type load_balancer_names: list :param load_balancer_names: A list of load balancer names. :type tags: dict :param tags: A dictionary containing the name/value pairs. If you want to create only a tag name, the value for that tag should be the empty string (e.g. ''). ''' params = {} conn.build_list_params(params, load_balancer_names, 'LoadBalancerNames.member.%d') _build_tag_param_list(params, tags) return conn.get_status('AddTags', params, verb='POST') def _remove_tags(conn, load_balancer_names, tags): ''' Delete metadata tags for the specified resource ids. :type load_balancer_names: list :param load_balancer_names: A list of load balancer names. :type tags: list :param tags: A list containing just tag names for the tags to be deleted. ''' params = {} conn.build_list_params(params, load_balancer_names, 'LoadBalancerNames.member.%d') conn.build_list_params(params, tags, 'Tags.member.%d.Key') return conn.get_status('RemoveTags', params, verb='POST')
saltstack/salt
salt/modules/boto_elb.py
delete_policy
python
def delete_policy(name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Delete an ELB policy. .. versionadded:: 2016.3.0 CLI example: .. code-block:: bash salt myminion boto_elb.delete_policy myelb mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not exists(name, region, key, keyid, profile): return True try: conn.delete_lb_policy(name, policy_name) log.info('Deleted policy %s on ELB %s', policy_name, name) return True except boto.exception.BotoServerError as e: log.error('Failed to delete policy %s on ELB %s: %s', policy_name, name, e.message, exc_info_on_loglevel=logging.DEBUG) return False
Delete an ELB policy. .. versionadded:: 2016.3.0 CLI example: .. code-block:: bash salt myminion boto_elb.delete_policy myelb mypolicy
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_elb.py#L879-L904
[ "def exists(name, region=None, key=None, keyid=None, profile=None):\n '''\n Check to see if an ELB exists.\n\n CLI example:\n\n .. code-block:: bash\n\n salt myminion boto_elb.exists myelb region=us-east-1\n '''\n conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)\n\n try:\n elb = conn.get_all_load_balancers(load_balancer_names=[name])\n if elb:\n return True\n else:\n log.debug('The load balancer does not exist in region %s', region)\n return False\n except boto.exception.BotoServerError as error:\n log.warning(error)\n return False\n" ]
# -*- coding: utf-8 -*- ''' Connection module for Amazon ELB .. versionadded:: 2014.7.0 :configuration: This module accepts explicit elb credentials but can also utilize IAM roles assigned to the instance through Instance Profiles. Dynamic credentials are then automatically obtained from AWS API and no further configuration is necessary. More Information available at: .. code-block:: text http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/iam-roles-for-amazon-ec2.html If IAM roles are not used you need to specify them either in a pillar or in the minion's config file: .. code-block:: yaml elb.keyid: GKTADJGHEIQSXMKKRBJ08H elb.key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs A region may also be specified in the configuration: .. code-block:: yaml elb.region: us-east-1 If a region is not specified, the default is us-east-1. It's also possible to specify key, keyid and region via a profile, either as a passed in dict, or as a string to pull from pillars or minion config: .. code-block:: yaml myprofile: keyid: GKTADJGHEIQSXMKKRBJ08H key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs region: us-east-1 :depends: boto >= 2.33.0 ''' # keep lint from choking on _get_conn and _cache_id # pylint: disable=E0602 from __future__ import absolute_import, print_function, unicode_literals # Import Python libs import logging import time log = logging.getLogger(__name__) # Import Salt libs import salt.utils.json import salt.utils.odict as odict import salt.utils.versions # Import third party libs from salt.ext import six try: import boto import boto.ec2 # pylint: enable=unused-import from boto.ec2.elb import HealthCheck from boto.ec2.elb.attributes import AccessLogAttribute from boto.ec2.elb.attributes import ConnectionDrainingAttribute from boto.ec2.elb.attributes import ConnectionSettingAttribute from boto.ec2.elb.attributes import CrossZoneLoadBalancingAttribute logging.getLogger('boto').setLevel(logging.CRITICAL) HAS_BOTO = True except ImportError: HAS_BOTO = False def __virtual__(): ''' Only load if boto libraries exist. ''' # connection settings were added in 2.33.0 has_boto_reqs = salt.utils.versions.check_boto_reqs( boto_ver='2.33.0', check_boto3=False ) if has_boto_reqs is True: __utils__['boto.assign_funcs'](__name__, 'elb', module='ec2.elb', pack=__salt__) return has_boto_reqs def exists(name, region=None, key=None, keyid=None, profile=None): ''' Check to see if an ELB exists. CLI example: .. code-block:: bash salt myminion boto_elb.exists myelb region=us-east-1 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: elb = conn.get_all_load_balancers(load_balancer_names=[name]) if elb: return True else: log.debug('The load balancer does not exist in region %s', region) return False except boto.exception.BotoServerError as error: log.warning(error) return False def get_all_elbs(region=None, key=None, keyid=None, profile=None): ''' Return all load balancers associated with an account CLI example: .. code-block:: bash salt myminion boto_elb.get_all_elbs region=us-east-1 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: return [e for e in conn.get_all_load_balancers()] except boto.exception.BotoServerError as error: log.warning(error) return [] def list_elbs(region=None, key=None, keyid=None, profile=None): ''' Return names of all load balancers associated with an account CLI example: .. code-block:: bash salt myminion boto_elb.list_elbs region=us-east-1 ''' return [e.name for e in get_all_elbs(region=region, key=key, keyid=keyid, profile=profile)] def get_elb_config(name, region=None, key=None, keyid=None, profile=None): ''' Get an ELB configuration. CLI example: .. code-block:: bash salt myminion boto_elb.exists myelb region=us-east-1 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) retries = 30 while retries: try: lb = conn.get_all_load_balancers(load_balancer_names=[name]) lb = lb[0] ret = {} ret['availability_zones'] = lb.availability_zones listeners = [] for _listener in lb.listeners: listener_dict = {} listener_dict['elb_port'] = _listener.load_balancer_port listener_dict['elb_protocol'] = _listener.protocol listener_dict['instance_port'] = _listener.instance_port listener_dict['instance_protocol'] = _listener.instance_protocol listener_dict['policies'] = _listener.policy_names if _listener.ssl_certificate_id: listener_dict['certificate'] = _listener.ssl_certificate_id listeners.append(listener_dict) ret['listeners'] = listeners backends = [] for _backend in lb.backends: bs_dict = {} bs_dict['instance_port'] = _backend.instance_port bs_dict['policies'] = [p.policy_name for p in _backend.policies] backends.append(bs_dict) ret['backends'] = backends ret['subnets'] = lb.subnets ret['security_groups'] = lb.security_groups ret['scheme'] = lb.scheme ret['dns_name'] = lb.dns_name ret['tags'] = _get_all_tags(conn, name) lb_policy_lists = [ lb.policies.app_cookie_stickiness_policies, lb.policies.lb_cookie_stickiness_policies, lb.policies.other_policies ] policies = [] for policy_list in lb_policy_lists: policies += [p.policy_name for p in policy_list] ret['policies'] = policies return ret except boto.exception.BotoServerError as error: if error.error_code == 'Throttling': log.debug('Throttled by AWS API, will retry in 5 seconds.') time.sleep(5) retries -= 1 continue log.error('Error fetching config for ELB %s: %s', name, error.message) log.error(error) return {} return {} def listener_dict_to_tuple(listener): ''' Convert an ELB listener dict into a listener tuple used by certain parts of the AWS ELB API. CLI example: .. code-block:: bash salt myminion boto_elb.listener_dict_to_tuple '{"elb_port":80,"instance_port":80,"elb_protocol":"HTTP"}' ''' # We define all listeners as complex listeners. if 'instance_protocol' not in listener: instance_protocol = listener['elb_protocol'].upper() else: instance_protocol = listener['instance_protocol'].upper() listener_tuple = [listener['elb_port'], listener['instance_port'], listener['elb_protocol'], instance_protocol] if 'certificate' in listener: listener_tuple.append(listener['certificate']) return tuple(listener_tuple) def create(name, availability_zones, listeners, subnets=None, security_groups=None, scheme='internet-facing', region=None, key=None, keyid=None, profile=None): ''' Create an ELB CLI example to create an ELB: .. code-block:: bash salt myminion boto_elb.create myelb '["us-east-1a", "us-east-1e"]' '{"elb_port": 443, "elb_protocol": "HTTPS", ...}' region=us-east-1 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if exists(name, region, key, keyid, profile): return True if isinstance(availability_zones, six.string_types): availability_zones = salt.utils.json.loads(availability_zones) if isinstance(listeners, six.string_types): listeners = salt.utils.json.loads(listeners) _complex_listeners = [] for listener in listeners: _complex_listeners.append(listener_dict_to_tuple(listener)) try: lb = conn.create_load_balancer(name=name, zones=availability_zones, subnets=subnets, security_groups=security_groups, scheme=scheme, complex_listeners=_complex_listeners) if lb: log.info('Created ELB %s', name) return True else: log.error('Failed to create ELB %s', name) return False except boto.exception.BotoServerError as error: log.error('Failed to create ELB %s: %s: %s', name, error.error_code, error.message, exc_info_on_loglevel=logging.DEBUG) return False def delete(name, region=None, key=None, keyid=None, profile=None): ''' Delete an ELB. CLI example to delete an ELB: .. code-block:: bash salt myminion boto_elb.delete myelb region=us-east-1 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not exists(name, region, key, keyid, profile): return True try: conn.delete_load_balancer(name) log.info('Deleted ELB %s.', name) return True except boto.exception.BotoServerError as error: log.error('Failed to delete ELB %s', name, exc_info_on_loglevel=logging.DEBUG) return False def create_listeners(name, listeners, region=None, key=None, keyid=None, profile=None): ''' Create listeners on an ELB. CLI example: .. code-block:: bash salt myminion boto_elb.create_listeners myelb '[["HTTPS", "HTTP", 443, 80, "arn:aws:iam::11 11111:server-certificate/mycert"]]' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if isinstance(listeners, six.string_types): listeners = salt.utils.json.loads(listeners) _complex_listeners = [] for listener in listeners: _complex_listeners.append(listener_dict_to_tuple(listener)) try: conn.create_load_balancer_listeners(name, [], _complex_listeners) log.info('Created ELB listeners on %s', name) return True except boto.exception.BotoServerError as error: log.error('Failed to create ELB listeners on %s: %s', name, error, exc_info_on_loglevel=logging.DEBUG) return False def delete_listeners(name, ports, region=None, key=None, keyid=None, profile=None): ''' Delete listeners on an ELB. CLI example: .. code-block:: bash salt myminion boto_elb.delete_listeners myelb '[80,443]' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if isinstance(ports, six.string_types): ports = salt.utils.json.loads(ports) try: conn.delete_load_balancer_listeners(name, ports) log.info('Deleted ELB listeners on %s', name) return True except boto.exception.BotoServerError as error: log.error('Failed to delete ELB listeners on %s: %s', name, error, exc_info_on_loglevel=logging.DEBUG) return False def apply_security_groups(name, security_groups, region=None, key=None, keyid=None, profile=None): ''' Apply security groups to ELB. CLI example: .. code-block:: bash salt myminion boto_elb.apply_security_groups myelb '["mysecgroup1"]' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if isinstance(security_groups, six.string_types): security_groups = salt.utils.json.loads(security_groups) try: conn.apply_security_groups_to_lb(name, security_groups) log.info('Applied security_groups on ELB %s', name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to appply security_groups on ELB %s: %s', name, e.message) return False def enable_availability_zones(name, availability_zones, region=None, key=None, keyid=None, profile=None): ''' Enable availability zones for ELB. CLI example: .. code-block:: bash salt myminion boto_elb.enable_availability_zones myelb '["us-east-1a"]' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if isinstance(availability_zones, six.string_types): availability_zones = salt.utils.json.loads(availability_zones) try: conn.enable_availability_zones(name, availability_zones) log.info('Enabled availability_zones on ELB %s', name) return True except boto.exception.BotoServerError as error: log.error('Failed to enable availability_zones on ELB %s: %s', name, error) return False def disable_availability_zones(name, availability_zones, region=None, key=None, keyid=None, profile=None): ''' Disable availability zones for ELB. CLI example: .. code-block:: bash salt myminion boto_elb.disable_availability_zones myelb '["us-east-1a"]' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if isinstance(availability_zones, six.string_types): availability_zones = salt.utils.json.loads(availability_zones) try: conn.disable_availability_zones(name, availability_zones) log.info('Disabled availability_zones on ELB %s', name) return True except boto.exception.BotoServerError as error: log.error('Failed to disable availability_zones on ELB %s: %s', name, error, exc_info_on_loglevel=logging.DEBUG) return False def attach_subnets(name, subnets, region=None, key=None, keyid=None, profile=None): ''' Attach ELB to subnets. CLI example: .. code-block:: bash salt myminion boto_elb.attach_subnets myelb '["mysubnet"]' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if isinstance(subnets, six.string_types): subnets = salt.utils.json.loads(subnets) try: conn.attach_lb_to_subnets(name, subnets) log.info('Attached ELB %s on subnets.', name) return True except boto.exception.BotoServerError as error: log.error('Failed to attach ELB %s on subnets: %s', name, error, exc_info_on_loglevel=logging.DEBUG) return False def detach_subnets(name, subnets, region=None, key=None, keyid=None, profile=None): ''' Detach ELB from subnets. CLI example: .. code-block:: bash salt myminion boto_elb.detach_subnets myelb '["mysubnet"]' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if isinstance(subnets, six.string_types): subnets = salt.utils.json.loads(subnets) try: conn.detach_lb_from_subnets(name, subnets) log.info('Detached ELB %s from subnets.', name) return True except boto.exception.BotoServerError as error: log.error('Failed to detach ELB %s from subnets: %s', name, error, exc_info_on_loglevel=logging.DEBUG) return False def get_attributes(name, region=None, key=None, keyid=None, profile=None): ''' Check to see if attributes are set on an ELB. CLI example: .. code-block:: bash salt myminion boto_elb.get_attributes myelb ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) retries = 30 while retries: try: lbattrs = conn.get_all_lb_attributes(name) ret = odict.OrderedDict() ret['access_log'] = odict.OrderedDict() ret['cross_zone_load_balancing'] = odict.OrderedDict() ret['connection_draining'] = odict.OrderedDict() ret['connecting_settings'] = odict.OrderedDict() al = lbattrs.access_log czlb = lbattrs.cross_zone_load_balancing cd = lbattrs.connection_draining cs = lbattrs.connecting_settings ret['access_log']['enabled'] = al.enabled ret['access_log']['s3_bucket_name'] = al.s3_bucket_name ret['access_log']['s3_bucket_prefix'] = al.s3_bucket_prefix ret['access_log']['emit_interval'] = al.emit_interval ret['cross_zone_load_balancing']['enabled'] = czlb.enabled ret['connection_draining']['enabled'] = cd.enabled ret['connection_draining']['timeout'] = cd.timeout ret['connecting_settings']['idle_timeout'] = cs.idle_timeout return ret except boto.exception.BotoServerError as e: if e.error_code == 'Throttling': log.debug("Throttled by AWS API, will retry in 5 seconds...") time.sleep(5) retries -= 1 continue log.error('ELB %s does not exist: %s', name, e.message) return {} return {} def set_attributes(name, attributes, region=None, key=None, keyid=None, profile=None): ''' Set attributes on an ELB. name (string) Name of the ELB instance to set attributes for attributes A dict of attributes to set. Valid attributes are: access_log (dict) enabled (bool) Enable storage of access logs. s3_bucket_name (string) The name of the S3 bucket to place logs. s3_bucket_prefix (string) Prefix for the log file name. emit_interval (int) Interval for storing logs in S3 in minutes. Valid values are 5 and 60. connection_draining (dict) enabled (bool) Enable connection draining. timeout (int) Maximum allowed time in seconds for sending existing connections to an instance that is deregistering or unhealthy. Default is 300. cross_zone_load_balancing (dict) enabled (bool) Enable cross-zone load balancing. CLI example to set attributes on an ELB: .. code-block:: bash salt myminion boto_elb.set_attributes myelb '{"access_log": {"enabled": "true", "s3_bucket_name": "mybucket", "s3_bucket_prefix": "mylogs/", "emit_interval": "5"}}' region=us-east-1 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) al = attributes.get('access_log', {}) czlb = attributes.get('cross_zone_load_balancing', {}) cd = attributes.get('connection_draining', {}) cs = attributes.get('connecting_settings', {}) if not al and not czlb and not cd and not cs: log.error('No supported attributes for ELB.') return False if al: _al = AccessLogAttribute() _al.enabled = al.get('enabled', False) if not _al.enabled: msg = 'Access log attribute configured, but enabled config missing' log.error(msg) return False _al.s3_bucket_name = al.get('s3_bucket_name', None) _al.s3_bucket_prefix = al.get('s3_bucket_prefix', None) _al.emit_interval = al.get('emit_interval', None) added_attr = conn.modify_lb_attribute(name, 'accessLog', _al) if added_attr: log.info('Added access_log attribute to %s elb.', name) else: log.error('Failed to add access_log attribute to %s elb.', name) return False if czlb: _czlb = CrossZoneLoadBalancingAttribute() _czlb.enabled = czlb['enabled'] added_attr = conn.modify_lb_attribute(name, 'crossZoneLoadBalancing', _czlb.enabled) if added_attr: log.info('Added cross_zone_load_balancing attribute to %s elb.', name) else: log.error('Failed to add cross_zone_load_balancing attribute.') return False if cd: _cd = ConnectionDrainingAttribute() _cd.enabled = cd['enabled'] _cd.timeout = cd.get('timeout', 300) added_attr = conn.modify_lb_attribute(name, 'connectionDraining', _cd) if added_attr: log.info('Added connection_draining attribute to %s elb.', name) else: log.error('Failed to add connection_draining attribute.') return False if cs: _cs = ConnectionSettingAttribute() _cs.idle_timeout = cs.get('idle_timeout', 60) added_attr = conn.modify_lb_attribute(name, 'connectingSettings', _cs) if added_attr: log.info('Added connecting_settings attribute to %s elb.', name) else: log.error('Failed to add connecting_settings attribute.') return False return True def get_health_check(name, region=None, key=None, keyid=None, profile=None): ''' Get the health check configured for this ELB. CLI example: .. code-block:: bash salt myminion boto_elb.get_health_check myelb ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) retries = 30 while True: try: lb = conn.get_all_load_balancers(load_balancer_names=[name]) lb = lb[0] ret = odict.OrderedDict() hc = lb.health_check ret['interval'] = hc.interval ret['target'] = hc.target ret['healthy_threshold'] = hc.healthy_threshold ret['timeout'] = hc.timeout ret['unhealthy_threshold'] = hc.unhealthy_threshold return ret except boto.exception.BotoServerError as e: if retries and e.code == 'Throttling': log.debug('Throttled by AWS API, will retry in 5 seconds.') time.sleep(5) retries -= 1 continue log.error('ELB %s not found.', name, exc_info_on_logleve=logging.DEBUG) return {} def set_health_check(name, health_check, region=None, key=None, keyid=None, profile=None): ''' Set attributes on an ELB. CLI example to set attributes on an ELB: .. code-block:: bash salt myminion boto_elb.set_health_check myelb '{"target": "HTTP:80/"}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) retries = 30 hc = HealthCheck(**health_check) while True: try: conn.configure_health_check(name, hc) log.info('Configured health check on ELB %s', name) return True except boto.exception.BotoServerError as error: if retries and e.code == 'Throttling': log.debug('Throttled by AWS API, will retry in 5 seconds.') time.sleep(5) retries -= 1 continue log.exception('Failed to configure health check on ELB %s', name) return False def register_instances(name, instances, region=None, key=None, keyid=None, profile=None): ''' Register instances with an ELB. Instances is either a string instance id or a list of string instance id's. Returns: - ``True``: instance(s) registered successfully - ``False``: instance(s) failed to be registered CLI example: .. code-block:: bash salt myminion boto_elb.register_instances myelb instance_id salt myminion boto_elb.register_instances myelb "[instance_id,instance_id]" ''' # convert instances to list type, enabling consistent use of instances # variable throughout the register_instances method if isinstance(instances, six.string_types) or isinstance(instances, six.text_type): instances = [instances] conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: registered_instances = conn.register_instances(name, instances) except boto.exception.BotoServerError as error: log.warning(error) return False registered_instance_ids = [instance.id for instance in registered_instances] # register_failues is a set that will contain any instances that were not # able to be registered with the given ELB register_failures = set(instances).difference(set(registered_instance_ids)) if register_failures: log.warning('Instance(s): %s not registered with ELB %s.', list(register_failures), name) register_result = False else: register_result = True return register_result def deregister_instances(name, instances, region=None, key=None, keyid=None, profile=None): ''' Deregister instances with an ELB. Instances is either a string instance id or a list of string instance id's. Returns: - ``True``: instance(s) deregistered successfully - ``False``: instance(s) failed to be deregistered - ``None``: instance(s) not valid or not registered, no action taken CLI example: .. code-block:: bash salt myminion boto_elb.deregister_instances myelb instance_id salt myminion boto_elb.deregister_instances myelb "[instance_id, instance_id]" ''' # convert instances to list type, enabling consistent use of instances # variable throughout the deregister_instances method if isinstance(instances, six.string_types) or isinstance(instances, six.text_type): instances = [instances] conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: registered_instances = conn.deregister_instances(name, instances) except boto.exception.BotoServerError as error: # if the instance(s) given as an argument are not members of the ELB # boto returns error.error_code == 'InvalidInstance' # deregister_instances returns "None" because the instances are # effectively deregistered from ELB if error.error_code == 'InvalidInstance': log.warning( 'One or more of instance(s) %s are not part of ELB %s. ' 'deregister_instances not performed.', instances, name ) return None else: log.warning(error) return False registered_instance_ids = [instance.id for instance in registered_instances] # deregister_failures is a set that will contain any instances that were # unable to be deregistered from the given ELB deregister_failures = set(instances).intersection(set(registered_instance_ids)) if deregister_failures: log.warning( 'Instance(s): %s not deregistered from ELB %s.', list(deregister_failures), name ) deregister_result = False else: deregister_result = True return deregister_result def set_instances(name, instances, test=False, region=None, key=None, keyid=None, profile=None): ''' Set the instances assigned to an ELB to exactly the list given CLI example: .. code-block:: bash salt myminion boto_elb.set_instances myelb region=us-east-1 instances="[instance_id,instance_id]" ''' ret = True current = set([i['instance_id'] for i in get_instance_health(name, region, key, keyid, profile)]) desired = set(instances) add = desired - current remove = current - desired if test: return bool(add or remove) if remove: if deregister_instances(name, list(remove), region, key, keyid, profile) is False: ret = False if add: if register_instances(name, list(add), region, key, keyid, profile) is False: ret = False return ret def get_instance_health(name, region=None, key=None, keyid=None, profile=None, instances=None): ''' Get a list of instances and their health state CLI example: .. code-block:: bash salt myminion boto_elb.get_instance_health myelb salt myminion boto_elb.get_instance_health myelb region=us-east-1 instances="[instance_id,instance_id]" ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: instance_states = conn.describe_instance_health(name, instances) ret = [] for _instance in instance_states: ret.append({'instance_id': _instance.instance_id, 'description': _instance.description, 'state': _instance.state, 'reason_code': _instance.reason_code }) return ret except boto.exception.BotoServerError as error: log.debug(error) return [] def create_policy(name, policy_name, policy_type, policy, region=None, key=None, keyid=None, profile=None): ''' Create an ELB policy. .. versionadded:: 2016.3.0 CLI example: .. code-block:: bash salt myminion boto_elb.create_policy myelb mypolicy LBCookieStickinessPolicyType '{"CookieExpirationPeriod": 3600}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not exists(name, region, key, keyid, profile): return False try: success = conn.create_lb_policy(name, policy_name, policy_type, policy) if success: log.info('Created policy %s on ELB %s', policy_name, name) return True else: log.error('Failed to create policy %s on ELB %s', policy_name, name) return False except boto.exception.BotoServerError as e: log.error('Failed to create policy %s on ELB %s: %s', policy_name, name, e.message, exc_info_on_loglevel=logging.DEBUG) return False def set_listener_policy(name, port, policies=None, region=None, key=None, keyid=None, profile=None): ''' Set the policies of an ELB listener. .. versionadded:: 2016.3.0 CLI example: .. code-block:: Bash salt myminion boto_elb.set_listener_policy myelb 443 "[policy1,policy2]" ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not exists(name, region, key, keyid, profile): return True if policies is None: policies = [] try: conn.set_lb_policies_of_listener(name, port, policies) log.info('Set policies %s on ELB %s listener %s', policies, name, port) except boto.exception.BotoServerError as e: log.info('Failed to set policy %s on ELB %s listener %s: %s', policies, name, port, e.message, exc_info_on_loglevel=logging.DEBUG) return False return True def set_backend_policy(name, port, policies=None, region=None, key=None, keyid=None, profile=None): ''' Set the policies of an ELB backend server. CLI example: salt myminion boto_elb.set_backend_policy myelb 443 "[policy1,policy2]" ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not exists(name, region, key, keyid, profile): return True if policies is None: policies = [] try: conn.set_lb_policies_of_backend_server(name, port, policies) log.info('Set policies %s on ELB %s backend server %s', policies, name, port) except boto.exception.BotoServerError as e: log.info('Failed to set policy %s on ELB %s backend server %s: %s', policies, name, port, e.message, exc_info_on_loglevel=logging.DEBUG) return False return True def set_tags(name, tags, region=None, key=None, keyid=None, profile=None): ''' Add the tags on an ELB .. versionadded:: 2016.3.0 name name of the ELB tags dict of name/value pair tags CLI Example: .. code-block:: bash salt myminion boto_elb.set_tags my-elb-name "{'Tag1': 'Value', 'Tag2': 'Another Value'}" ''' if exists(name, region, key, keyid, profile): conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) ret = _add_tags(conn, name, tags) return ret else: return False def delete_tags(name, tags, region=None, key=None, keyid=None, profile=None): ''' Add the tags on an ELB name name of the ELB tags list of tags to remove CLI Example: .. code-block:: bash salt myminion boto_elb.delete_tags my-elb-name ['TagToRemove1', 'TagToRemove2'] ''' if exists(name, region, key, keyid, profile): conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) ret = _remove_tags(conn, name, tags) return ret else: return False def _build_tag_param_list(params, tags): ''' helper function to build a tag parameter list to send ''' keys = sorted(tags.keys()) i = 1 for key in keys: value = tags[key] params['Tags.member.{0}.Key'.format(i)] = key if value is not None: params['Tags.member.{0}.Value'.format(i)] = value i += 1 def _get_all_tags(conn, load_balancer_names=None): ''' Retrieve all the metadata tags associated with your ELB(s). :type load_balancer_names: list :param load_balancer_names: An optional list of load balancer names. :rtype: list :return: A list of :class:`boto.ec2.elb.tag.Tag` objects ''' params = {} if load_balancer_names: conn.build_list_params(params, load_balancer_names, 'LoadBalancerNames.member.%d') tags = conn.get_object( 'DescribeTags', params, __utils__['boto_elb_tag.get_tag_descriptions'](), verb='POST' ) if tags[load_balancer_names]: return tags[load_balancer_names] else: return None def _add_tags(conn, load_balancer_names, tags): ''' Create new metadata tags for the specified resource ids. :type load_balancer_names: list :param load_balancer_names: A list of load balancer names. :type tags: dict :param tags: A dictionary containing the name/value pairs. If you want to create only a tag name, the value for that tag should be the empty string (e.g. ''). ''' params = {} conn.build_list_params(params, load_balancer_names, 'LoadBalancerNames.member.%d') _build_tag_param_list(params, tags) return conn.get_status('AddTags', params, verb='POST') def _remove_tags(conn, load_balancer_names, tags): ''' Delete metadata tags for the specified resource ids. :type load_balancer_names: list :param load_balancer_names: A list of load balancer names. :type tags: list :param tags: A list containing just tag names for the tags to be deleted. ''' params = {} conn.build_list_params(params, load_balancer_names, 'LoadBalancerNames.member.%d') conn.build_list_params(params, tags, 'Tags.member.%d.Key') return conn.get_status('RemoveTags', params, verb='POST')
saltstack/salt
salt/modules/boto_elb.py
set_listener_policy
python
def set_listener_policy(name, port, policies=None, region=None, key=None, keyid=None, profile=None): ''' Set the policies of an ELB listener. .. versionadded:: 2016.3.0 CLI example: .. code-block:: Bash salt myminion boto_elb.set_listener_policy myelb 443 "[policy1,policy2]" ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not exists(name, region, key, keyid, profile): return True if policies is None: policies = [] try: conn.set_lb_policies_of_listener(name, port, policies) log.info('Set policies %s on ELB %s listener %s', policies, name, port) except boto.exception.BotoServerError as e: log.info('Failed to set policy %s on ELB %s listener %s: %s', policies, name, port, e.message, exc_info_on_loglevel=logging.DEBUG) return False return True
Set the policies of an ELB listener. .. versionadded:: 2016.3.0 CLI example: .. code-block:: Bash salt myminion boto_elb.set_listener_policy myelb 443 "[policy1,policy2]"
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_elb.py#L907-L934
[ "def exists(name, region=None, key=None, keyid=None, profile=None):\n '''\n Check to see if an ELB exists.\n\n CLI example:\n\n .. code-block:: bash\n\n salt myminion boto_elb.exists myelb region=us-east-1\n '''\n conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)\n\n try:\n elb = conn.get_all_load_balancers(load_balancer_names=[name])\n if elb:\n return True\n else:\n log.debug('The load balancer does not exist in region %s', region)\n return False\n except boto.exception.BotoServerError as error:\n log.warning(error)\n return False\n" ]
# -*- coding: utf-8 -*- ''' Connection module for Amazon ELB .. versionadded:: 2014.7.0 :configuration: This module accepts explicit elb credentials but can also utilize IAM roles assigned to the instance through Instance Profiles. Dynamic credentials are then automatically obtained from AWS API and no further configuration is necessary. More Information available at: .. code-block:: text http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/iam-roles-for-amazon-ec2.html If IAM roles are not used you need to specify them either in a pillar or in the minion's config file: .. code-block:: yaml elb.keyid: GKTADJGHEIQSXMKKRBJ08H elb.key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs A region may also be specified in the configuration: .. code-block:: yaml elb.region: us-east-1 If a region is not specified, the default is us-east-1. It's also possible to specify key, keyid and region via a profile, either as a passed in dict, or as a string to pull from pillars or minion config: .. code-block:: yaml myprofile: keyid: GKTADJGHEIQSXMKKRBJ08H key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs region: us-east-1 :depends: boto >= 2.33.0 ''' # keep lint from choking on _get_conn and _cache_id # pylint: disable=E0602 from __future__ import absolute_import, print_function, unicode_literals # Import Python libs import logging import time log = logging.getLogger(__name__) # Import Salt libs import salt.utils.json import salt.utils.odict as odict import salt.utils.versions # Import third party libs from salt.ext import six try: import boto import boto.ec2 # pylint: enable=unused-import from boto.ec2.elb import HealthCheck from boto.ec2.elb.attributes import AccessLogAttribute from boto.ec2.elb.attributes import ConnectionDrainingAttribute from boto.ec2.elb.attributes import ConnectionSettingAttribute from boto.ec2.elb.attributes import CrossZoneLoadBalancingAttribute logging.getLogger('boto').setLevel(logging.CRITICAL) HAS_BOTO = True except ImportError: HAS_BOTO = False def __virtual__(): ''' Only load if boto libraries exist. ''' # connection settings were added in 2.33.0 has_boto_reqs = salt.utils.versions.check_boto_reqs( boto_ver='2.33.0', check_boto3=False ) if has_boto_reqs is True: __utils__['boto.assign_funcs'](__name__, 'elb', module='ec2.elb', pack=__salt__) return has_boto_reqs def exists(name, region=None, key=None, keyid=None, profile=None): ''' Check to see if an ELB exists. CLI example: .. code-block:: bash salt myminion boto_elb.exists myelb region=us-east-1 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: elb = conn.get_all_load_balancers(load_balancer_names=[name]) if elb: return True else: log.debug('The load balancer does not exist in region %s', region) return False except boto.exception.BotoServerError as error: log.warning(error) return False def get_all_elbs(region=None, key=None, keyid=None, profile=None): ''' Return all load balancers associated with an account CLI example: .. code-block:: bash salt myminion boto_elb.get_all_elbs region=us-east-1 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: return [e for e in conn.get_all_load_balancers()] except boto.exception.BotoServerError as error: log.warning(error) return [] def list_elbs(region=None, key=None, keyid=None, profile=None): ''' Return names of all load balancers associated with an account CLI example: .. code-block:: bash salt myminion boto_elb.list_elbs region=us-east-1 ''' return [e.name for e in get_all_elbs(region=region, key=key, keyid=keyid, profile=profile)] def get_elb_config(name, region=None, key=None, keyid=None, profile=None): ''' Get an ELB configuration. CLI example: .. code-block:: bash salt myminion boto_elb.exists myelb region=us-east-1 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) retries = 30 while retries: try: lb = conn.get_all_load_balancers(load_balancer_names=[name]) lb = lb[0] ret = {} ret['availability_zones'] = lb.availability_zones listeners = [] for _listener in lb.listeners: listener_dict = {} listener_dict['elb_port'] = _listener.load_balancer_port listener_dict['elb_protocol'] = _listener.protocol listener_dict['instance_port'] = _listener.instance_port listener_dict['instance_protocol'] = _listener.instance_protocol listener_dict['policies'] = _listener.policy_names if _listener.ssl_certificate_id: listener_dict['certificate'] = _listener.ssl_certificate_id listeners.append(listener_dict) ret['listeners'] = listeners backends = [] for _backend in lb.backends: bs_dict = {} bs_dict['instance_port'] = _backend.instance_port bs_dict['policies'] = [p.policy_name for p in _backend.policies] backends.append(bs_dict) ret['backends'] = backends ret['subnets'] = lb.subnets ret['security_groups'] = lb.security_groups ret['scheme'] = lb.scheme ret['dns_name'] = lb.dns_name ret['tags'] = _get_all_tags(conn, name) lb_policy_lists = [ lb.policies.app_cookie_stickiness_policies, lb.policies.lb_cookie_stickiness_policies, lb.policies.other_policies ] policies = [] for policy_list in lb_policy_lists: policies += [p.policy_name for p in policy_list] ret['policies'] = policies return ret except boto.exception.BotoServerError as error: if error.error_code == 'Throttling': log.debug('Throttled by AWS API, will retry in 5 seconds.') time.sleep(5) retries -= 1 continue log.error('Error fetching config for ELB %s: %s', name, error.message) log.error(error) return {} return {} def listener_dict_to_tuple(listener): ''' Convert an ELB listener dict into a listener tuple used by certain parts of the AWS ELB API. CLI example: .. code-block:: bash salt myminion boto_elb.listener_dict_to_tuple '{"elb_port":80,"instance_port":80,"elb_protocol":"HTTP"}' ''' # We define all listeners as complex listeners. if 'instance_protocol' not in listener: instance_protocol = listener['elb_protocol'].upper() else: instance_protocol = listener['instance_protocol'].upper() listener_tuple = [listener['elb_port'], listener['instance_port'], listener['elb_protocol'], instance_protocol] if 'certificate' in listener: listener_tuple.append(listener['certificate']) return tuple(listener_tuple) def create(name, availability_zones, listeners, subnets=None, security_groups=None, scheme='internet-facing', region=None, key=None, keyid=None, profile=None): ''' Create an ELB CLI example to create an ELB: .. code-block:: bash salt myminion boto_elb.create myelb '["us-east-1a", "us-east-1e"]' '{"elb_port": 443, "elb_protocol": "HTTPS", ...}' region=us-east-1 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if exists(name, region, key, keyid, profile): return True if isinstance(availability_zones, six.string_types): availability_zones = salt.utils.json.loads(availability_zones) if isinstance(listeners, six.string_types): listeners = salt.utils.json.loads(listeners) _complex_listeners = [] for listener in listeners: _complex_listeners.append(listener_dict_to_tuple(listener)) try: lb = conn.create_load_balancer(name=name, zones=availability_zones, subnets=subnets, security_groups=security_groups, scheme=scheme, complex_listeners=_complex_listeners) if lb: log.info('Created ELB %s', name) return True else: log.error('Failed to create ELB %s', name) return False except boto.exception.BotoServerError as error: log.error('Failed to create ELB %s: %s: %s', name, error.error_code, error.message, exc_info_on_loglevel=logging.DEBUG) return False def delete(name, region=None, key=None, keyid=None, profile=None): ''' Delete an ELB. CLI example to delete an ELB: .. code-block:: bash salt myminion boto_elb.delete myelb region=us-east-1 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not exists(name, region, key, keyid, profile): return True try: conn.delete_load_balancer(name) log.info('Deleted ELB %s.', name) return True except boto.exception.BotoServerError as error: log.error('Failed to delete ELB %s', name, exc_info_on_loglevel=logging.DEBUG) return False def create_listeners(name, listeners, region=None, key=None, keyid=None, profile=None): ''' Create listeners on an ELB. CLI example: .. code-block:: bash salt myminion boto_elb.create_listeners myelb '[["HTTPS", "HTTP", 443, 80, "arn:aws:iam::11 11111:server-certificate/mycert"]]' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if isinstance(listeners, six.string_types): listeners = salt.utils.json.loads(listeners) _complex_listeners = [] for listener in listeners: _complex_listeners.append(listener_dict_to_tuple(listener)) try: conn.create_load_balancer_listeners(name, [], _complex_listeners) log.info('Created ELB listeners on %s', name) return True except boto.exception.BotoServerError as error: log.error('Failed to create ELB listeners on %s: %s', name, error, exc_info_on_loglevel=logging.DEBUG) return False def delete_listeners(name, ports, region=None, key=None, keyid=None, profile=None): ''' Delete listeners on an ELB. CLI example: .. code-block:: bash salt myminion boto_elb.delete_listeners myelb '[80,443]' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if isinstance(ports, six.string_types): ports = salt.utils.json.loads(ports) try: conn.delete_load_balancer_listeners(name, ports) log.info('Deleted ELB listeners on %s', name) return True except boto.exception.BotoServerError as error: log.error('Failed to delete ELB listeners on %s: %s', name, error, exc_info_on_loglevel=logging.DEBUG) return False def apply_security_groups(name, security_groups, region=None, key=None, keyid=None, profile=None): ''' Apply security groups to ELB. CLI example: .. code-block:: bash salt myminion boto_elb.apply_security_groups myelb '["mysecgroup1"]' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if isinstance(security_groups, six.string_types): security_groups = salt.utils.json.loads(security_groups) try: conn.apply_security_groups_to_lb(name, security_groups) log.info('Applied security_groups on ELB %s', name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to appply security_groups on ELB %s: %s', name, e.message) return False def enable_availability_zones(name, availability_zones, region=None, key=None, keyid=None, profile=None): ''' Enable availability zones for ELB. CLI example: .. code-block:: bash salt myminion boto_elb.enable_availability_zones myelb '["us-east-1a"]' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if isinstance(availability_zones, six.string_types): availability_zones = salt.utils.json.loads(availability_zones) try: conn.enable_availability_zones(name, availability_zones) log.info('Enabled availability_zones on ELB %s', name) return True except boto.exception.BotoServerError as error: log.error('Failed to enable availability_zones on ELB %s: %s', name, error) return False def disable_availability_zones(name, availability_zones, region=None, key=None, keyid=None, profile=None): ''' Disable availability zones for ELB. CLI example: .. code-block:: bash salt myminion boto_elb.disable_availability_zones myelb '["us-east-1a"]' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if isinstance(availability_zones, six.string_types): availability_zones = salt.utils.json.loads(availability_zones) try: conn.disable_availability_zones(name, availability_zones) log.info('Disabled availability_zones on ELB %s', name) return True except boto.exception.BotoServerError as error: log.error('Failed to disable availability_zones on ELB %s: %s', name, error, exc_info_on_loglevel=logging.DEBUG) return False def attach_subnets(name, subnets, region=None, key=None, keyid=None, profile=None): ''' Attach ELB to subnets. CLI example: .. code-block:: bash salt myminion boto_elb.attach_subnets myelb '["mysubnet"]' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if isinstance(subnets, six.string_types): subnets = salt.utils.json.loads(subnets) try: conn.attach_lb_to_subnets(name, subnets) log.info('Attached ELB %s on subnets.', name) return True except boto.exception.BotoServerError as error: log.error('Failed to attach ELB %s on subnets: %s', name, error, exc_info_on_loglevel=logging.DEBUG) return False def detach_subnets(name, subnets, region=None, key=None, keyid=None, profile=None): ''' Detach ELB from subnets. CLI example: .. code-block:: bash salt myminion boto_elb.detach_subnets myelb '["mysubnet"]' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if isinstance(subnets, six.string_types): subnets = salt.utils.json.loads(subnets) try: conn.detach_lb_from_subnets(name, subnets) log.info('Detached ELB %s from subnets.', name) return True except boto.exception.BotoServerError as error: log.error('Failed to detach ELB %s from subnets: %s', name, error, exc_info_on_loglevel=logging.DEBUG) return False def get_attributes(name, region=None, key=None, keyid=None, profile=None): ''' Check to see if attributes are set on an ELB. CLI example: .. code-block:: bash salt myminion boto_elb.get_attributes myelb ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) retries = 30 while retries: try: lbattrs = conn.get_all_lb_attributes(name) ret = odict.OrderedDict() ret['access_log'] = odict.OrderedDict() ret['cross_zone_load_balancing'] = odict.OrderedDict() ret['connection_draining'] = odict.OrderedDict() ret['connecting_settings'] = odict.OrderedDict() al = lbattrs.access_log czlb = lbattrs.cross_zone_load_balancing cd = lbattrs.connection_draining cs = lbattrs.connecting_settings ret['access_log']['enabled'] = al.enabled ret['access_log']['s3_bucket_name'] = al.s3_bucket_name ret['access_log']['s3_bucket_prefix'] = al.s3_bucket_prefix ret['access_log']['emit_interval'] = al.emit_interval ret['cross_zone_load_balancing']['enabled'] = czlb.enabled ret['connection_draining']['enabled'] = cd.enabled ret['connection_draining']['timeout'] = cd.timeout ret['connecting_settings']['idle_timeout'] = cs.idle_timeout return ret except boto.exception.BotoServerError as e: if e.error_code == 'Throttling': log.debug("Throttled by AWS API, will retry in 5 seconds...") time.sleep(5) retries -= 1 continue log.error('ELB %s does not exist: %s', name, e.message) return {} return {} def set_attributes(name, attributes, region=None, key=None, keyid=None, profile=None): ''' Set attributes on an ELB. name (string) Name of the ELB instance to set attributes for attributes A dict of attributes to set. Valid attributes are: access_log (dict) enabled (bool) Enable storage of access logs. s3_bucket_name (string) The name of the S3 bucket to place logs. s3_bucket_prefix (string) Prefix for the log file name. emit_interval (int) Interval for storing logs in S3 in minutes. Valid values are 5 and 60. connection_draining (dict) enabled (bool) Enable connection draining. timeout (int) Maximum allowed time in seconds for sending existing connections to an instance that is deregistering or unhealthy. Default is 300. cross_zone_load_balancing (dict) enabled (bool) Enable cross-zone load balancing. CLI example to set attributes on an ELB: .. code-block:: bash salt myminion boto_elb.set_attributes myelb '{"access_log": {"enabled": "true", "s3_bucket_name": "mybucket", "s3_bucket_prefix": "mylogs/", "emit_interval": "5"}}' region=us-east-1 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) al = attributes.get('access_log', {}) czlb = attributes.get('cross_zone_load_balancing', {}) cd = attributes.get('connection_draining', {}) cs = attributes.get('connecting_settings', {}) if not al and not czlb and not cd and not cs: log.error('No supported attributes for ELB.') return False if al: _al = AccessLogAttribute() _al.enabled = al.get('enabled', False) if not _al.enabled: msg = 'Access log attribute configured, but enabled config missing' log.error(msg) return False _al.s3_bucket_name = al.get('s3_bucket_name', None) _al.s3_bucket_prefix = al.get('s3_bucket_prefix', None) _al.emit_interval = al.get('emit_interval', None) added_attr = conn.modify_lb_attribute(name, 'accessLog', _al) if added_attr: log.info('Added access_log attribute to %s elb.', name) else: log.error('Failed to add access_log attribute to %s elb.', name) return False if czlb: _czlb = CrossZoneLoadBalancingAttribute() _czlb.enabled = czlb['enabled'] added_attr = conn.modify_lb_attribute(name, 'crossZoneLoadBalancing', _czlb.enabled) if added_attr: log.info('Added cross_zone_load_balancing attribute to %s elb.', name) else: log.error('Failed to add cross_zone_load_balancing attribute.') return False if cd: _cd = ConnectionDrainingAttribute() _cd.enabled = cd['enabled'] _cd.timeout = cd.get('timeout', 300) added_attr = conn.modify_lb_attribute(name, 'connectionDraining', _cd) if added_attr: log.info('Added connection_draining attribute to %s elb.', name) else: log.error('Failed to add connection_draining attribute.') return False if cs: _cs = ConnectionSettingAttribute() _cs.idle_timeout = cs.get('idle_timeout', 60) added_attr = conn.modify_lb_attribute(name, 'connectingSettings', _cs) if added_attr: log.info('Added connecting_settings attribute to %s elb.', name) else: log.error('Failed to add connecting_settings attribute.') return False return True def get_health_check(name, region=None, key=None, keyid=None, profile=None): ''' Get the health check configured for this ELB. CLI example: .. code-block:: bash salt myminion boto_elb.get_health_check myelb ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) retries = 30 while True: try: lb = conn.get_all_load_balancers(load_balancer_names=[name]) lb = lb[0] ret = odict.OrderedDict() hc = lb.health_check ret['interval'] = hc.interval ret['target'] = hc.target ret['healthy_threshold'] = hc.healthy_threshold ret['timeout'] = hc.timeout ret['unhealthy_threshold'] = hc.unhealthy_threshold return ret except boto.exception.BotoServerError as e: if retries and e.code == 'Throttling': log.debug('Throttled by AWS API, will retry in 5 seconds.') time.sleep(5) retries -= 1 continue log.error('ELB %s not found.', name, exc_info_on_logleve=logging.DEBUG) return {} def set_health_check(name, health_check, region=None, key=None, keyid=None, profile=None): ''' Set attributes on an ELB. CLI example to set attributes on an ELB: .. code-block:: bash salt myminion boto_elb.set_health_check myelb '{"target": "HTTP:80/"}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) retries = 30 hc = HealthCheck(**health_check) while True: try: conn.configure_health_check(name, hc) log.info('Configured health check on ELB %s', name) return True except boto.exception.BotoServerError as error: if retries and e.code == 'Throttling': log.debug('Throttled by AWS API, will retry in 5 seconds.') time.sleep(5) retries -= 1 continue log.exception('Failed to configure health check on ELB %s', name) return False def register_instances(name, instances, region=None, key=None, keyid=None, profile=None): ''' Register instances with an ELB. Instances is either a string instance id or a list of string instance id's. Returns: - ``True``: instance(s) registered successfully - ``False``: instance(s) failed to be registered CLI example: .. code-block:: bash salt myminion boto_elb.register_instances myelb instance_id salt myminion boto_elb.register_instances myelb "[instance_id,instance_id]" ''' # convert instances to list type, enabling consistent use of instances # variable throughout the register_instances method if isinstance(instances, six.string_types) or isinstance(instances, six.text_type): instances = [instances] conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: registered_instances = conn.register_instances(name, instances) except boto.exception.BotoServerError as error: log.warning(error) return False registered_instance_ids = [instance.id for instance in registered_instances] # register_failues is a set that will contain any instances that were not # able to be registered with the given ELB register_failures = set(instances).difference(set(registered_instance_ids)) if register_failures: log.warning('Instance(s): %s not registered with ELB %s.', list(register_failures), name) register_result = False else: register_result = True return register_result def deregister_instances(name, instances, region=None, key=None, keyid=None, profile=None): ''' Deregister instances with an ELB. Instances is either a string instance id or a list of string instance id's. Returns: - ``True``: instance(s) deregistered successfully - ``False``: instance(s) failed to be deregistered - ``None``: instance(s) not valid or not registered, no action taken CLI example: .. code-block:: bash salt myminion boto_elb.deregister_instances myelb instance_id salt myminion boto_elb.deregister_instances myelb "[instance_id, instance_id]" ''' # convert instances to list type, enabling consistent use of instances # variable throughout the deregister_instances method if isinstance(instances, six.string_types) or isinstance(instances, six.text_type): instances = [instances] conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: registered_instances = conn.deregister_instances(name, instances) except boto.exception.BotoServerError as error: # if the instance(s) given as an argument are not members of the ELB # boto returns error.error_code == 'InvalidInstance' # deregister_instances returns "None" because the instances are # effectively deregistered from ELB if error.error_code == 'InvalidInstance': log.warning( 'One or more of instance(s) %s are not part of ELB %s. ' 'deregister_instances not performed.', instances, name ) return None else: log.warning(error) return False registered_instance_ids = [instance.id for instance in registered_instances] # deregister_failures is a set that will contain any instances that were # unable to be deregistered from the given ELB deregister_failures = set(instances).intersection(set(registered_instance_ids)) if deregister_failures: log.warning( 'Instance(s): %s not deregistered from ELB %s.', list(deregister_failures), name ) deregister_result = False else: deregister_result = True return deregister_result def set_instances(name, instances, test=False, region=None, key=None, keyid=None, profile=None): ''' Set the instances assigned to an ELB to exactly the list given CLI example: .. code-block:: bash salt myminion boto_elb.set_instances myelb region=us-east-1 instances="[instance_id,instance_id]" ''' ret = True current = set([i['instance_id'] for i in get_instance_health(name, region, key, keyid, profile)]) desired = set(instances) add = desired - current remove = current - desired if test: return bool(add or remove) if remove: if deregister_instances(name, list(remove), region, key, keyid, profile) is False: ret = False if add: if register_instances(name, list(add), region, key, keyid, profile) is False: ret = False return ret def get_instance_health(name, region=None, key=None, keyid=None, profile=None, instances=None): ''' Get a list of instances and their health state CLI example: .. code-block:: bash salt myminion boto_elb.get_instance_health myelb salt myminion boto_elb.get_instance_health myelb region=us-east-1 instances="[instance_id,instance_id]" ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: instance_states = conn.describe_instance_health(name, instances) ret = [] for _instance in instance_states: ret.append({'instance_id': _instance.instance_id, 'description': _instance.description, 'state': _instance.state, 'reason_code': _instance.reason_code }) return ret except boto.exception.BotoServerError as error: log.debug(error) return [] def create_policy(name, policy_name, policy_type, policy, region=None, key=None, keyid=None, profile=None): ''' Create an ELB policy. .. versionadded:: 2016.3.0 CLI example: .. code-block:: bash salt myminion boto_elb.create_policy myelb mypolicy LBCookieStickinessPolicyType '{"CookieExpirationPeriod": 3600}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not exists(name, region, key, keyid, profile): return False try: success = conn.create_lb_policy(name, policy_name, policy_type, policy) if success: log.info('Created policy %s on ELB %s', policy_name, name) return True else: log.error('Failed to create policy %s on ELB %s', policy_name, name) return False except boto.exception.BotoServerError as e: log.error('Failed to create policy %s on ELB %s: %s', policy_name, name, e.message, exc_info_on_loglevel=logging.DEBUG) return False def delete_policy(name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Delete an ELB policy. .. versionadded:: 2016.3.0 CLI example: .. code-block:: bash salt myminion boto_elb.delete_policy myelb mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not exists(name, region, key, keyid, profile): return True try: conn.delete_lb_policy(name, policy_name) log.info('Deleted policy %s on ELB %s', policy_name, name) return True except boto.exception.BotoServerError as e: log.error('Failed to delete policy %s on ELB %s: %s', policy_name, name, e.message, exc_info_on_loglevel=logging.DEBUG) return False def set_backend_policy(name, port, policies=None, region=None, key=None, keyid=None, profile=None): ''' Set the policies of an ELB backend server. CLI example: salt myminion boto_elb.set_backend_policy myelb 443 "[policy1,policy2]" ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not exists(name, region, key, keyid, profile): return True if policies is None: policies = [] try: conn.set_lb_policies_of_backend_server(name, port, policies) log.info('Set policies %s on ELB %s backend server %s', policies, name, port) except boto.exception.BotoServerError as e: log.info('Failed to set policy %s on ELB %s backend server %s: %s', policies, name, port, e.message, exc_info_on_loglevel=logging.DEBUG) return False return True def set_tags(name, tags, region=None, key=None, keyid=None, profile=None): ''' Add the tags on an ELB .. versionadded:: 2016.3.0 name name of the ELB tags dict of name/value pair tags CLI Example: .. code-block:: bash salt myminion boto_elb.set_tags my-elb-name "{'Tag1': 'Value', 'Tag2': 'Another Value'}" ''' if exists(name, region, key, keyid, profile): conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) ret = _add_tags(conn, name, tags) return ret else: return False def delete_tags(name, tags, region=None, key=None, keyid=None, profile=None): ''' Add the tags on an ELB name name of the ELB tags list of tags to remove CLI Example: .. code-block:: bash salt myminion boto_elb.delete_tags my-elb-name ['TagToRemove1', 'TagToRemove2'] ''' if exists(name, region, key, keyid, profile): conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) ret = _remove_tags(conn, name, tags) return ret else: return False def _build_tag_param_list(params, tags): ''' helper function to build a tag parameter list to send ''' keys = sorted(tags.keys()) i = 1 for key in keys: value = tags[key] params['Tags.member.{0}.Key'.format(i)] = key if value is not None: params['Tags.member.{0}.Value'.format(i)] = value i += 1 def _get_all_tags(conn, load_balancer_names=None): ''' Retrieve all the metadata tags associated with your ELB(s). :type load_balancer_names: list :param load_balancer_names: An optional list of load balancer names. :rtype: list :return: A list of :class:`boto.ec2.elb.tag.Tag` objects ''' params = {} if load_balancer_names: conn.build_list_params(params, load_balancer_names, 'LoadBalancerNames.member.%d') tags = conn.get_object( 'DescribeTags', params, __utils__['boto_elb_tag.get_tag_descriptions'](), verb='POST' ) if tags[load_balancer_names]: return tags[load_balancer_names] else: return None def _add_tags(conn, load_balancer_names, tags): ''' Create new metadata tags for the specified resource ids. :type load_balancer_names: list :param load_balancer_names: A list of load balancer names. :type tags: dict :param tags: A dictionary containing the name/value pairs. If you want to create only a tag name, the value for that tag should be the empty string (e.g. ''). ''' params = {} conn.build_list_params(params, load_balancer_names, 'LoadBalancerNames.member.%d') _build_tag_param_list(params, tags) return conn.get_status('AddTags', params, verb='POST') def _remove_tags(conn, load_balancer_names, tags): ''' Delete metadata tags for the specified resource ids. :type load_balancer_names: list :param load_balancer_names: A list of load balancer names. :type tags: list :param tags: A list containing just tag names for the tags to be deleted. ''' params = {} conn.build_list_params(params, load_balancer_names, 'LoadBalancerNames.member.%d') conn.build_list_params(params, tags, 'Tags.member.%d.Key') return conn.get_status('RemoveTags', params, verb='POST')
saltstack/salt
salt/modules/boto_elb.py
set_tags
python
def set_tags(name, tags, region=None, key=None, keyid=None, profile=None): ''' Add the tags on an ELB .. versionadded:: 2016.3.0 name name of the ELB tags dict of name/value pair tags CLI Example: .. code-block:: bash salt myminion boto_elb.set_tags my-elb-name "{'Tag1': 'Value', 'Tag2': 'Another Value'}" ''' if exists(name, region, key, keyid, profile): conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) ret = _add_tags(conn, name, tags) return ret else: return False
Add the tags on an ELB .. versionadded:: 2016.3.0 name name of the ELB tags dict of name/value pair tags CLI Example: .. code-block:: bash salt myminion boto_elb.set_tags my-elb-name "{'Tag1': 'Value', 'Tag2': 'Another Value'}"
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_elb.py#L964-L988
[ "def exists(name, region=None, key=None, keyid=None, profile=None):\n '''\n Check to see if an ELB exists.\n\n CLI example:\n\n .. code-block:: bash\n\n salt myminion boto_elb.exists myelb region=us-east-1\n '''\n conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)\n\n try:\n elb = conn.get_all_load_balancers(load_balancer_names=[name])\n if elb:\n return True\n else:\n log.debug('The load balancer does not exist in region %s', region)\n return False\n except boto.exception.BotoServerError as error:\n log.warning(error)\n return False\n", "def _add_tags(conn, load_balancer_names, tags):\n '''\n Create new metadata tags for the specified resource ids.\n\n :type load_balancer_names: list\n :param load_balancer_names: A list of load balancer names.\n\n :type tags: dict\n :param tags: A dictionary containing the name/value pairs.\n If you want to create only a tag name, the\n value for that tag should be the empty string\n (e.g. '').\n '''\n params = {}\n conn.build_list_params(params, load_balancer_names,\n 'LoadBalancerNames.member.%d')\n _build_tag_param_list(params, tags)\n return conn.get_status('AddTags', params, verb='POST')\n" ]
# -*- coding: utf-8 -*- ''' Connection module for Amazon ELB .. versionadded:: 2014.7.0 :configuration: This module accepts explicit elb credentials but can also utilize IAM roles assigned to the instance through Instance Profiles. Dynamic credentials are then automatically obtained from AWS API and no further configuration is necessary. More Information available at: .. code-block:: text http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/iam-roles-for-amazon-ec2.html If IAM roles are not used you need to specify them either in a pillar or in the minion's config file: .. code-block:: yaml elb.keyid: GKTADJGHEIQSXMKKRBJ08H elb.key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs A region may also be specified in the configuration: .. code-block:: yaml elb.region: us-east-1 If a region is not specified, the default is us-east-1. It's also possible to specify key, keyid and region via a profile, either as a passed in dict, or as a string to pull from pillars or minion config: .. code-block:: yaml myprofile: keyid: GKTADJGHEIQSXMKKRBJ08H key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs region: us-east-1 :depends: boto >= 2.33.0 ''' # keep lint from choking on _get_conn and _cache_id # pylint: disable=E0602 from __future__ import absolute_import, print_function, unicode_literals # Import Python libs import logging import time log = logging.getLogger(__name__) # Import Salt libs import salt.utils.json import salt.utils.odict as odict import salt.utils.versions # Import third party libs from salt.ext import six try: import boto import boto.ec2 # pylint: enable=unused-import from boto.ec2.elb import HealthCheck from boto.ec2.elb.attributes import AccessLogAttribute from boto.ec2.elb.attributes import ConnectionDrainingAttribute from boto.ec2.elb.attributes import ConnectionSettingAttribute from boto.ec2.elb.attributes import CrossZoneLoadBalancingAttribute logging.getLogger('boto').setLevel(logging.CRITICAL) HAS_BOTO = True except ImportError: HAS_BOTO = False def __virtual__(): ''' Only load if boto libraries exist. ''' # connection settings were added in 2.33.0 has_boto_reqs = salt.utils.versions.check_boto_reqs( boto_ver='2.33.0', check_boto3=False ) if has_boto_reqs is True: __utils__['boto.assign_funcs'](__name__, 'elb', module='ec2.elb', pack=__salt__) return has_boto_reqs def exists(name, region=None, key=None, keyid=None, profile=None): ''' Check to see if an ELB exists. CLI example: .. code-block:: bash salt myminion boto_elb.exists myelb region=us-east-1 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: elb = conn.get_all_load_balancers(load_balancer_names=[name]) if elb: return True else: log.debug('The load balancer does not exist in region %s', region) return False except boto.exception.BotoServerError as error: log.warning(error) return False def get_all_elbs(region=None, key=None, keyid=None, profile=None): ''' Return all load balancers associated with an account CLI example: .. code-block:: bash salt myminion boto_elb.get_all_elbs region=us-east-1 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: return [e for e in conn.get_all_load_balancers()] except boto.exception.BotoServerError as error: log.warning(error) return [] def list_elbs(region=None, key=None, keyid=None, profile=None): ''' Return names of all load balancers associated with an account CLI example: .. code-block:: bash salt myminion boto_elb.list_elbs region=us-east-1 ''' return [e.name for e in get_all_elbs(region=region, key=key, keyid=keyid, profile=profile)] def get_elb_config(name, region=None, key=None, keyid=None, profile=None): ''' Get an ELB configuration. CLI example: .. code-block:: bash salt myminion boto_elb.exists myelb region=us-east-1 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) retries = 30 while retries: try: lb = conn.get_all_load_balancers(load_balancer_names=[name]) lb = lb[0] ret = {} ret['availability_zones'] = lb.availability_zones listeners = [] for _listener in lb.listeners: listener_dict = {} listener_dict['elb_port'] = _listener.load_balancer_port listener_dict['elb_protocol'] = _listener.protocol listener_dict['instance_port'] = _listener.instance_port listener_dict['instance_protocol'] = _listener.instance_protocol listener_dict['policies'] = _listener.policy_names if _listener.ssl_certificate_id: listener_dict['certificate'] = _listener.ssl_certificate_id listeners.append(listener_dict) ret['listeners'] = listeners backends = [] for _backend in lb.backends: bs_dict = {} bs_dict['instance_port'] = _backend.instance_port bs_dict['policies'] = [p.policy_name for p in _backend.policies] backends.append(bs_dict) ret['backends'] = backends ret['subnets'] = lb.subnets ret['security_groups'] = lb.security_groups ret['scheme'] = lb.scheme ret['dns_name'] = lb.dns_name ret['tags'] = _get_all_tags(conn, name) lb_policy_lists = [ lb.policies.app_cookie_stickiness_policies, lb.policies.lb_cookie_stickiness_policies, lb.policies.other_policies ] policies = [] for policy_list in lb_policy_lists: policies += [p.policy_name for p in policy_list] ret['policies'] = policies return ret except boto.exception.BotoServerError as error: if error.error_code == 'Throttling': log.debug('Throttled by AWS API, will retry in 5 seconds.') time.sleep(5) retries -= 1 continue log.error('Error fetching config for ELB %s: %s', name, error.message) log.error(error) return {} return {} def listener_dict_to_tuple(listener): ''' Convert an ELB listener dict into a listener tuple used by certain parts of the AWS ELB API. CLI example: .. code-block:: bash salt myminion boto_elb.listener_dict_to_tuple '{"elb_port":80,"instance_port":80,"elb_protocol":"HTTP"}' ''' # We define all listeners as complex listeners. if 'instance_protocol' not in listener: instance_protocol = listener['elb_protocol'].upper() else: instance_protocol = listener['instance_protocol'].upper() listener_tuple = [listener['elb_port'], listener['instance_port'], listener['elb_protocol'], instance_protocol] if 'certificate' in listener: listener_tuple.append(listener['certificate']) return tuple(listener_tuple) def create(name, availability_zones, listeners, subnets=None, security_groups=None, scheme='internet-facing', region=None, key=None, keyid=None, profile=None): ''' Create an ELB CLI example to create an ELB: .. code-block:: bash salt myminion boto_elb.create myelb '["us-east-1a", "us-east-1e"]' '{"elb_port": 443, "elb_protocol": "HTTPS", ...}' region=us-east-1 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if exists(name, region, key, keyid, profile): return True if isinstance(availability_zones, six.string_types): availability_zones = salt.utils.json.loads(availability_zones) if isinstance(listeners, six.string_types): listeners = salt.utils.json.loads(listeners) _complex_listeners = [] for listener in listeners: _complex_listeners.append(listener_dict_to_tuple(listener)) try: lb = conn.create_load_balancer(name=name, zones=availability_zones, subnets=subnets, security_groups=security_groups, scheme=scheme, complex_listeners=_complex_listeners) if lb: log.info('Created ELB %s', name) return True else: log.error('Failed to create ELB %s', name) return False except boto.exception.BotoServerError as error: log.error('Failed to create ELB %s: %s: %s', name, error.error_code, error.message, exc_info_on_loglevel=logging.DEBUG) return False def delete(name, region=None, key=None, keyid=None, profile=None): ''' Delete an ELB. CLI example to delete an ELB: .. code-block:: bash salt myminion boto_elb.delete myelb region=us-east-1 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not exists(name, region, key, keyid, profile): return True try: conn.delete_load_balancer(name) log.info('Deleted ELB %s.', name) return True except boto.exception.BotoServerError as error: log.error('Failed to delete ELB %s', name, exc_info_on_loglevel=logging.DEBUG) return False def create_listeners(name, listeners, region=None, key=None, keyid=None, profile=None): ''' Create listeners on an ELB. CLI example: .. code-block:: bash salt myminion boto_elb.create_listeners myelb '[["HTTPS", "HTTP", 443, 80, "arn:aws:iam::11 11111:server-certificate/mycert"]]' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if isinstance(listeners, six.string_types): listeners = salt.utils.json.loads(listeners) _complex_listeners = [] for listener in listeners: _complex_listeners.append(listener_dict_to_tuple(listener)) try: conn.create_load_balancer_listeners(name, [], _complex_listeners) log.info('Created ELB listeners on %s', name) return True except boto.exception.BotoServerError as error: log.error('Failed to create ELB listeners on %s: %s', name, error, exc_info_on_loglevel=logging.DEBUG) return False def delete_listeners(name, ports, region=None, key=None, keyid=None, profile=None): ''' Delete listeners on an ELB. CLI example: .. code-block:: bash salt myminion boto_elb.delete_listeners myelb '[80,443]' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if isinstance(ports, six.string_types): ports = salt.utils.json.loads(ports) try: conn.delete_load_balancer_listeners(name, ports) log.info('Deleted ELB listeners on %s', name) return True except boto.exception.BotoServerError as error: log.error('Failed to delete ELB listeners on %s: %s', name, error, exc_info_on_loglevel=logging.DEBUG) return False def apply_security_groups(name, security_groups, region=None, key=None, keyid=None, profile=None): ''' Apply security groups to ELB. CLI example: .. code-block:: bash salt myminion boto_elb.apply_security_groups myelb '["mysecgroup1"]' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if isinstance(security_groups, six.string_types): security_groups = salt.utils.json.loads(security_groups) try: conn.apply_security_groups_to_lb(name, security_groups) log.info('Applied security_groups on ELB %s', name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to appply security_groups on ELB %s: %s', name, e.message) return False def enable_availability_zones(name, availability_zones, region=None, key=None, keyid=None, profile=None): ''' Enable availability zones for ELB. CLI example: .. code-block:: bash salt myminion boto_elb.enable_availability_zones myelb '["us-east-1a"]' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if isinstance(availability_zones, six.string_types): availability_zones = salt.utils.json.loads(availability_zones) try: conn.enable_availability_zones(name, availability_zones) log.info('Enabled availability_zones on ELB %s', name) return True except boto.exception.BotoServerError as error: log.error('Failed to enable availability_zones on ELB %s: %s', name, error) return False def disable_availability_zones(name, availability_zones, region=None, key=None, keyid=None, profile=None): ''' Disable availability zones for ELB. CLI example: .. code-block:: bash salt myminion boto_elb.disable_availability_zones myelb '["us-east-1a"]' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if isinstance(availability_zones, six.string_types): availability_zones = salt.utils.json.loads(availability_zones) try: conn.disable_availability_zones(name, availability_zones) log.info('Disabled availability_zones on ELB %s', name) return True except boto.exception.BotoServerError as error: log.error('Failed to disable availability_zones on ELB %s: %s', name, error, exc_info_on_loglevel=logging.DEBUG) return False def attach_subnets(name, subnets, region=None, key=None, keyid=None, profile=None): ''' Attach ELB to subnets. CLI example: .. code-block:: bash salt myminion boto_elb.attach_subnets myelb '["mysubnet"]' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if isinstance(subnets, six.string_types): subnets = salt.utils.json.loads(subnets) try: conn.attach_lb_to_subnets(name, subnets) log.info('Attached ELB %s on subnets.', name) return True except boto.exception.BotoServerError as error: log.error('Failed to attach ELB %s on subnets: %s', name, error, exc_info_on_loglevel=logging.DEBUG) return False def detach_subnets(name, subnets, region=None, key=None, keyid=None, profile=None): ''' Detach ELB from subnets. CLI example: .. code-block:: bash salt myminion boto_elb.detach_subnets myelb '["mysubnet"]' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if isinstance(subnets, six.string_types): subnets = salt.utils.json.loads(subnets) try: conn.detach_lb_from_subnets(name, subnets) log.info('Detached ELB %s from subnets.', name) return True except boto.exception.BotoServerError as error: log.error('Failed to detach ELB %s from subnets: %s', name, error, exc_info_on_loglevel=logging.DEBUG) return False def get_attributes(name, region=None, key=None, keyid=None, profile=None): ''' Check to see if attributes are set on an ELB. CLI example: .. code-block:: bash salt myminion boto_elb.get_attributes myelb ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) retries = 30 while retries: try: lbattrs = conn.get_all_lb_attributes(name) ret = odict.OrderedDict() ret['access_log'] = odict.OrderedDict() ret['cross_zone_load_balancing'] = odict.OrderedDict() ret['connection_draining'] = odict.OrderedDict() ret['connecting_settings'] = odict.OrderedDict() al = lbattrs.access_log czlb = lbattrs.cross_zone_load_balancing cd = lbattrs.connection_draining cs = lbattrs.connecting_settings ret['access_log']['enabled'] = al.enabled ret['access_log']['s3_bucket_name'] = al.s3_bucket_name ret['access_log']['s3_bucket_prefix'] = al.s3_bucket_prefix ret['access_log']['emit_interval'] = al.emit_interval ret['cross_zone_load_balancing']['enabled'] = czlb.enabled ret['connection_draining']['enabled'] = cd.enabled ret['connection_draining']['timeout'] = cd.timeout ret['connecting_settings']['idle_timeout'] = cs.idle_timeout return ret except boto.exception.BotoServerError as e: if e.error_code == 'Throttling': log.debug("Throttled by AWS API, will retry in 5 seconds...") time.sleep(5) retries -= 1 continue log.error('ELB %s does not exist: %s', name, e.message) return {} return {} def set_attributes(name, attributes, region=None, key=None, keyid=None, profile=None): ''' Set attributes on an ELB. name (string) Name of the ELB instance to set attributes for attributes A dict of attributes to set. Valid attributes are: access_log (dict) enabled (bool) Enable storage of access logs. s3_bucket_name (string) The name of the S3 bucket to place logs. s3_bucket_prefix (string) Prefix for the log file name. emit_interval (int) Interval for storing logs in S3 in minutes. Valid values are 5 and 60. connection_draining (dict) enabled (bool) Enable connection draining. timeout (int) Maximum allowed time in seconds for sending existing connections to an instance that is deregistering or unhealthy. Default is 300. cross_zone_load_balancing (dict) enabled (bool) Enable cross-zone load balancing. CLI example to set attributes on an ELB: .. code-block:: bash salt myminion boto_elb.set_attributes myelb '{"access_log": {"enabled": "true", "s3_bucket_name": "mybucket", "s3_bucket_prefix": "mylogs/", "emit_interval": "5"}}' region=us-east-1 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) al = attributes.get('access_log', {}) czlb = attributes.get('cross_zone_load_balancing', {}) cd = attributes.get('connection_draining', {}) cs = attributes.get('connecting_settings', {}) if not al and not czlb and not cd and not cs: log.error('No supported attributes for ELB.') return False if al: _al = AccessLogAttribute() _al.enabled = al.get('enabled', False) if not _al.enabled: msg = 'Access log attribute configured, but enabled config missing' log.error(msg) return False _al.s3_bucket_name = al.get('s3_bucket_name', None) _al.s3_bucket_prefix = al.get('s3_bucket_prefix', None) _al.emit_interval = al.get('emit_interval', None) added_attr = conn.modify_lb_attribute(name, 'accessLog', _al) if added_attr: log.info('Added access_log attribute to %s elb.', name) else: log.error('Failed to add access_log attribute to %s elb.', name) return False if czlb: _czlb = CrossZoneLoadBalancingAttribute() _czlb.enabled = czlb['enabled'] added_attr = conn.modify_lb_attribute(name, 'crossZoneLoadBalancing', _czlb.enabled) if added_attr: log.info('Added cross_zone_load_balancing attribute to %s elb.', name) else: log.error('Failed to add cross_zone_load_balancing attribute.') return False if cd: _cd = ConnectionDrainingAttribute() _cd.enabled = cd['enabled'] _cd.timeout = cd.get('timeout', 300) added_attr = conn.modify_lb_attribute(name, 'connectionDraining', _cd) if added_attr: log.info('Added connection_draining attribute to %s elb.', name) else: log.error('Failed to add connection_draining attribute.') return False if cs: _cs = ConnectionSettingAttribute() _cs.idle_timeout = cs.get('idle_timeout', 60) added_attr = conn.modify_lb_attribute(name, 'connectingSettings', _cs) if added_attr: log.info('Added connecting_settings attribute to %s elb.', name) else: log.error('Failed to add connecting_settings attribute.') return False return True def get_health_check(name, region=None, key=None, keyid=None, profile=None): ''' Get the health check configured for this ELB. CLI example: .. code-block:: bash salt myminion boto_elb.get_health_check myelb ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) retries = 30 while True: try: lb = conn.get_all_load_balancers(load_balancer_names=[name]) lb = lb[0] ret = odict.OrderedDict() hc = lb.health_check ret['interval'] = hc.interval ret['target'] = hc.target ret['healthy_threshold'] = hc.healthy_threshold ret['timeout'] = hc.timeout ret['unhealthy_threshold'] = hc.unhealthy_threshold return ret except boto.exception.BotoServerError as e: if retries and e.code == 'Throttling': log.debug('Throttled by AWS API, will retry in 5 seconds.') time.sleep(5) retries -= 1 continue log.error('ELB %s not found.', name, exc_info_on_logleve=logging.DEBUG) return {} def set_health_check(name, health_check, region=None, key=None, keyid=None, profile=None): ''' Set attributes on an ELB. CLI example to set attributes on an ELB: .. code-block:: bash salt myminion boto_elb.set_health_check myelb '{"target": "HTTP:80/"}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) retries = 30 hc = HealthCheck(**health_check) while True: try: conn.configure_health_check(name, hc) log.info('Configured health check on ELB %s', name) return True except boto.exception.BotoServerError as error: if retries and e.code == 'Throttling': log.debug('Throttled by AWS API, will retry in 5 seconds.') time.sleep(5) retries -= 1 continue log.exception('Failed to configure health check on ELB %s', name) return False def register_instances(name, instances, region=None, key=None, keyid=None, profile=None): ''' Register instances with an ELB. Instances is either a string instance id or a list of string instance id's. Returns: - ``True``: instance(s) registered successfully - ``False``: instance(s) failed to be registered CLI example: .. code-block:: bash salt myminion boto_elb.register_instances myelb instance_id salt myminion boto_elb.register_instances myelb "[instance_id,instance_id]" ''' # convert instances to list type, enabling consistent use of instances # variable throughout the register_instances method if isinstance(instances, six.string_types) or isinstance(instances, six.text_type): instances = [instances] conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: registered_instances = conn.register_instances(name, instances) except boto.exception.BotoServerError as error: log.warning(error) return False registered_instance_ids = [instance.id for instance in registered_instances] # register_failues is a set that will contain any instances that were not # able to be registered with the given ELB register_failures = set(instances).difference(set(registered_instance_ids)) if register_failures: log.warning('Instance(s): %s not registered with ELB %s.', list(register_failures), name) register_result = False else: register_result = True return register_result def deregister_instances(name, instances, region=None, key=None, keyid=None, profile=None): ''' Deregister instances with an ELB. Instances is either a string instance id or a list of string instance id's. Returns: - ``True``: instance(s) deregistered successfully - ``False``: instance(s) failed to be deregistered - ``None``: instance(s) not valid or not registered, no action taken CLI example: .. code-block:: bash salt myminion boto_elb.deregister_instances myelb instance_id salt myminion boto_elb.deregister_instances myelb "[instance_id, instance_id]" ''' # convert instances to list type, enabling consistent use of instances # variable throughout the deregister_instances method if isinstance(instances, six.string_types) or isinstance(instances, six.text_type): instances = [instances] conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: registered_instances = conn.deregister_instances(name, instances) except boto.exception.BotoServerError as error: # if the instance(s) given as an argument are not members of the ELB # boto returns error.error_code == 'InvalidInstance' # deregister_instances returns "None" because the instances are # effectively deregistered from ELB if error.error_code == 'InvalidInstance': log.warning( 'One or more of instance(s) %s are not part of ELB %s. ' 'deregister_instances not performed.', instances, name ) return None else: log.warning(error) return False registered_instance_ids = [instance.id for instance in registered_instances] # deregister_failures is a set that will contain any instances that were # unable to be deregistered from the given ELB deregister_failures = set(instances).intersection(set(registered_instance_ids)) if deregister_failures: log.warning( 'Instance(s): %s not deregistered from ELB %s.', list(deregister_failures), name ) deregister_result = False else: deregister_result = True return deregister_result def set_instances(name, instances, test=False, region=None, key=None, keyid=None, profile=None): ''' Set the instances assigned to an ELB to exactly the list given CLI example: .. code-block:: bash salt myminion boto_elb.set_instances myelb region=us-east-1 instances="[instance_id,instance_id]" ''' ret = True current = set([i['instance_id'] for i in get_instance_health(name, region, key, keyid, profile)]) desired = set(instances) add = desired - current remove = current - desired if test: return bool(add or remove) if remove: if deregister_instances(name, list(remove), region, key, keyid, profile) is False: ret = False if add: if register_instances(name, list(add), region, key, keyid, profile) is False: ret = False return ret def get_instance_health(name, region=None, key=None, keyid=None, profile=None, instances=None): ''' Get a list of instances and their health state CLI example: .. code-block:: bash salt myminion boto_elb.get_instance_health myelb salt myminion boto_elb.get_instance_health myelb region=us-east-1 instances="[instance_id,instance_id]" ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: instance_states = conn.describe_instance_health(name, instances) ret = [] for _instance in instance_states: ret.append({'instance_id': _instance.instance_id, 'description': _instance.description, 'state': _instance.state, 'reason_code': _instance.reason_code }) return ret except boto.exception.BotoServerError as error: log.debug(error) return [] def create_policy(name, policy_name, policy_type, policy, region=None, key=None, keyid=None, profile=None): ''' Create an ELB policy. .. versionadded:: 2016.3.0 CLI example: .. code-block:: bash salt myminion boto_elb.create_policy myelb mypolicy LBCookieStickinessPolicyType '{"CookieExpirationPeriod": 3600}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not exists(name, region, key, keyid, profile): return False try: success = conn.create_lb_policy(name, policy_name, policy_type, policy) if success: log.info('Created policy %s on ELB %s', policy_name, name) return True else: log.error('Failed to create policy %s on ELB %s', policy_name, name) return False except boto.exception.BotoServerError as e: log.error('Failed to create policy %s on ELB %s: %s', policy_name, name, e.message, exc_info_on_loglevel=logging.DEBUG) return False def delete_policy(name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Delete an ELB policy. .. versionadded:: 2016.3.0 CLI example: .. code-block:: bash salt myminion boto_elb.delete_policy myelb mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not exists(name, region, key, keyid, profile): return True try: conn.delete_lb_policy(name, policy_name) log.info('Deleted policy %s on ELB %s', policy_name, name) return True except boto.exception.BotoServerError as e: log.error('Failed to delete policy %s on ELB %s: %s', policy_name, name, e.message, exc_info_on_loglevel=logging.DEBUG) return False def set_listener_policy(name, port, policies=None, region=None, key=None, keyid=None, profile=None): ''' Set the policies of an ELB listener. .. versionadded:: 2016.3.0 CLI example: .. code-block:: Bash salt myminion boto_elb.set_listener_policy myelb 443 "[policy1,policy2]" ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not exists(name, region, key, keyid, profile): return True if policies is None: policies = [] try: conn.set_lb_policies_of_listener(name, port, policies) log.info('Set policies %s on ELB %s listener %s', policies, name, port) except boto.exception.BotoServerError as e: log.info('Failed to set policy %s on ELB %s listener %s: %s', policies, name, port, e.message, exc_info_on_loglevel=logging.DEBUG) return False return True def set_backend_policy(name, port, policies=None, region=None, key=None, keyid=None, profile=None): ''' Set the policies of an ELB backend server. CLI example: salt myminion boto_elb.set_backend_policy myelb 443 "[policy1,policy2]" ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not exists(name, region, key, keyid, profile): return True if policies is None: policies = [] try: conn.set_lb_policies_of_backend_server(name, port, policies) log.info('Set policies %s on ELB %s backend server %s', policies, name, port) except boto.exception.BotoServerError as e: log.info('Failed to set policy %s on ELB %s backend server %s: %s', policies, name, port, e.message, exc_info_on_loglevel=logging.DEBUG) return False return True def delete_tags(name, tags, region=None, key=None, keyid=None, profile=None): ''' Add the tags on an ELB name name of the ELB tags list of tags to remove CLI Example: .. code-block:: bash salt myminion boto_elb.delete_tags my-elb-name ['TagToRemove1', 'TagToRemove2'] ''' if exists(name, region, key, keyid, profile): conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) ret = _remove_tags(conn, name, tags) return ret else: return False def _build_tag_param_list(params, tags): ''' helper function to build a tag parameter list to send ''' keys = sorted(tags.keys()) i = 1 for key in keys: value = tags[key] params['Tags.member.{0}.Key'.format(i)] = key if value is not None: params['Tags.member.{0}.Value'.format(i)] = value i += 1 def _get_all_tags(conn, load_balancer_names=None): ''' Retrieve all the metadata tags associated with your ELB(s). :type load_balancer_names: list :param load_balancer_names: An optional list of load balancer names. :rtype: list :return: A list of :class:`boto.ec2.elb.tag.Tag` objects ''' params = {} if load_balancer_names: conn.build_list_params(params, load_balancer_names, 'LoadBalancerNames.member.%d') tags = conn.get_object( 'DescribeTags', params, __utils__['boto_elb_tag.get_tag_descriptions'](), verb='POST' ) if tags[load_balancer_names]: return tags[load_balancer_names] else: return None def _add_tags(conn, load_balancer_names, tags): ''' Create new metadata tags for the specified resource ids. :type load_balancer_names: list :param load_balancer_names: A list of load balancer names. :type tags: dict :param tags: A dictionary containing the name/value pairs. If you want to create only a tag name, the value for that tag should be the empty string (e.g. ''). ''' params = {} conn.build_list_params(params, load_balancer_names, 'LoadBalancerNames.member.%d') _build_tag_param_list(params, tags) return conn.get_status('AddTags', params, verb='POST') def _remove_tags(conn, load_balancer_names, tags): ''' Delete metadata tags for the specified resource ids. :type load_balancer_names: list :param load_balancer_names: A list of load balancer names. :type tags: list :param tags: A list containing just tag names for the tags to be deleted. ''' params = {} conn.build_list_params(params, load_balancer_names, 'LoadBalancerNames.member.%d') conn.build_list_params(params, tags, 'Tags.member.%d.Key') return conn.get_status('RemoveTags', params, verb='POST')
saltstack/salt
salt/modules/boto_elb.py
delete_tags
python
def delete_tags(name, tags, region=None, key=None, keyid=None, profile=None): ''' Add the tags on an ELB name name of the ELB tags list of tags to remove CLI Example: .. code-block:: bash salt myminion boto_elb.delete_tags my-elb-name ['TagToRemove1', 'TagToRemove2'] ''' if exists(name, region, key, keyid, profile): conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) ret = _remove_tags(conn, name, tags) return ret else: return False
Add the tags on an ELB name name of the ELB tags list of tags to remove CLI Example: .. code-block:: bash salt myminion boto_elb.delete_tags my-elb-name ['TagToRemove1', 'TagToRemove2']
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_elb.py#L991-L1012
[ "def exists(name, region=None, key=None, keyid=None, profile=None):\n '''\n Check to see if an ELB exists.\n\n CLI example:\n\n .. code-block:: bash\n\n salt myminion boto_elb.exists myelb region=us-east-1\n '''\n conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)\n\n try:\n elb = conn.get_all_load_balancers(load_balancer_names=[name])\n if elb:\n return True\n else:\n log.debug('The load balancer does not exist in region %s', region)\n return False\n except boto.exception.BotoServerError as error:\n log.warning(error)\n return False\n", "def _remove_tags(conn, load_balancer_names, tags):\n '''\n Delete metadata tags for the specified resource ids.\n\n :type load_balancer_names: list\n :param load_balancer_names: A list of load balancer names.\n\n :type tags: list\n :param tags: A list containing just tag names for the tags to be\n deleted.\n '''\n params = {}\n conn.build_list_params(params, load_balancer_names,\n 'LoadBalancerNames.member.%d')\n conn.build_list_params(params, tags,\n 'Tags.member.%d.Key')\n return conn.get_status('RemoveTags', params, verb='POST')\n" ]
# -*- coding: utf-8 -*- ''' Connection module for Amazon ELB .. versionadded:: 2014.7.0 :configuration: This module accepts explicit elb credentials but can also utilize IAM roles assigned to the instance through Instance Profiles. Dynamic credentials are then automatically obtained from AWS API and no further configuration is necessary. More Information available at: .. code-block:: text http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/iam-roles-for-amazon-ec2.html If IAM roles are not used you need to specify them either in a pillar or in the minion's config file: .. code-block:: yaml elb.keyid: GKTADJGHEIQSXMKKRBJ08H elb.key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs A region may also be specified in the configuration: .. code-block:: yaml elb.region: us-east-1 If a region is not specified, the default is us-east-1. It's also possible to specify key, keyid and region via a profile, either as a passed in dict, or as a string to pull from pillars or minion config: .. code-block:: yaml myprofile: keyid: GKTADJGHEIQSXMKKRBJ08H key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs region: us-east-1 :depends: boto >= 2.33.0 ''' # keep lint from choking on _get_conn and _cache_id # pylint: disable=E0602 from __future__ import absolute_import, print_function, unicode_literals # Import Python libs import logging import time log = logging.getLogger(__name__) # Import Salt libs import salt.utils.json import salt.utils.odict as odict import salt.utils.versions # Import third party libs from salt.ext import six try: import boto import boto.ec2 # pylint: enable=unused-import from boto.ec2.elb import HealthCheck from boto.ec2.elb.attributes import AccessLogAttribute from boto.ec2.elb.attributes import ConnectionDrainingAttribute from boto.ec2.elb.attributes import ConnectionSettingAttribute from boto.ec2.elb.attributes import CrossZoneLoadBalancingAttribute logging.getLogger('boto').setLevel(logging.CRITICAL) HAS_BOTO = True except ImportError: HAS_BOTO = False def __virtual__(): ''' Only load if boto libraries exist. ''' # connection settings were added in 2.33.0 has_boto_reqs = salt.utils.versions.check_boto_reqs( boto_ver='2.33.0', check_boto3=False ) if has_boto_reqs is True: __utils__['boto.assign_funcs'](__name__, 'elb', module='ec2.elb', pack=__salt__) return has_boto_reqs def exists(name, region=None, key=None, keyid=None, profile=None): ''' Check to see if an ELB exists. CLI example: .. code-block:: bash salt myminion boto_elb.exists myelb region=us-east-1 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: elb = conn.get_all_load_balancers(load_balancer_names=[name]) if elb: return True else: log.debug('The load balancer does not exist in region %s', region) return False except boto.exception.BotoServerError as error: log.warning(error) return False def get_all_elbs(region=None, key=None, keyid=None, profile=None): ''' Return all load balancers associated with an account CLI example: .. code-block:: bash salt myminion boto_elb.get_all_elbs region=us-east-1 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: return [e for e in conn.get_all_load_balancers()] except boto.exception.BotoServerError as error: log.warning(error) return [] def list_elbs(region=None, key=None, keyid=None, profile=None): ''' Return names of all load balancers associated with an account CLI example: .. code-block:: bash salt myminion boto_elb.list_elbs region=us-east-1 ''' return [e.name for e in get_all_elbs(region=region, key=key, keyid=keyid, profile=profile)] def get_elb_config(name, region=None, key=None, keyid=None, profile=None): ''' Get an ELB configuration. CLI example: .. code-block:: bash salt myminion boto_elb.exists myelb region=us-east-1 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) retries = 30 while retries: try: lb = conn.get_all_load_balancers(load_balancer_names=[name]) lb = lb[0] ret = {} ret['availability_zones'] = lb.availability_zones listeners = [] for _listener in lb.listeners: listener_dict = {} listener_dict['elb_port'] = _listener.load_balancer_port listener_dict['elb_protocol'] = _listener.protocol listener_dict['instance_port'] = _listener.instance_port listener_dict['instance_protocol'] = _listener.instance_protocol listener_dict['policies'] = _listener.policy_names if _listener.ssl_certificate_id: listener_dict['certificate'] = _listener.ssl_certificate_id listeners.append(listener_dict) ret['listeners'] = listeners backends = [] for _backend in lb.backends: bs_dict = {} bs_dict['instance_port'] = _backend.instance_port bs_dict['policies'] = [p.policy_name for p in _backend.policies] backends.append(bs_dict) ret['backends'] = backends ret['subnets'] = lb.subnets ret['security_groups'] = lb.security_groups ret['scheme'] = lb.scheme ret['dns_name'] = lb.dns_name ret['tags'] = _get_all_tags(conn, name) lb_policy_lists = [ lb.policies.app_cookie_stickiness_policies, lb.policies.lb_cookie_stickiness_policies, lb.policies.other_policies ] policies = [] for policy_list in lb_policy_lists: policies += [p.policy_name for p in policy_list] ret['policies'] = policies return ret except boto.exception.BotoServerError as error: if error.error_code == 'Throttling': log.debug('Throttled by AWS API, will retry in 5 seconds.') time.sleep(5) retries -= 1 continue log.error('Error fetching config for ELB %s: %s', name, error.message) log.error(error) return {} return {} def listener_dict_to_tuple(listener): ''' Convert an ELB listener dict into a listener tuple used by certain parts of the AWS ELB API. CLI example: .. code-block:: bash salt myminion boto_elb.listener_dict_to_tuple '{"elb_port":80,"instance_port":80,"elb_protocol":"HTTP"}' ''' # We define all listeners as complex listeners. if 'instance_protocol' not in listener: instance_protocol = listener['elb_protocol'].upper() else: instance_protocol = listener['instance_protocol'].upper() listener_tuple = [listener['elb_port'], listener['instance_port'], listener['elb_protocol'], instance_protocol] if 'certificate' in listener: listener_tuple.append(listener['certificate']) return tuple(listener_tuple) def create(name, availability_zones, listeners, subnets=None, security_groups=None, scheme='internet-facing', region=None, key=None, keyid=None, profile=None): ''' Create an ELB CLI example to create an ELB: .. code-block:: bash salt myminion boto_elb.create myelb '["us-east-1a", "us-east-1e"]' '{"elb_port": 443, "elb_protocol": "HTTPS", ...}' region=us-east-1 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if exists(name, region, key, keyid, profile): return True if isinstance(availability_zones, six.string_types): availability_zones = salt.utils.json.loads(availability_zones) if isinstance(listeners, six.string_types): listeners = salt.utils.json.loads(listeners) _complex_listeners = [] for listener in listeners: _complex_listeners.append(listener_dict_to_tuple(listener)) try: lb = conn.create_load_balancer(name=name, zones=availability_zones, subnets=subnets, security_groups=security_groups, scheme=scheme, complex_listeners=_complex_listeners) if lb: log.info('Created ELB %s', name) return True else: log.error('Failed to create ELB %s', name) return False except boto.exception.BotoServerError as error: log.error('Failed to create ELB %s: %s: %s', name, error.error_code, error.message, exc_info_on_loglevel=logging.DEBUG) return False def delete(name, region=None, key=None, keyid=None, profile=None): ''' Delete an ELB. CLI example to delete an ELB: .. code-block:: bash salt myminion boto_elb.delete myelb region=us-east-1 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not exists(name, region, key, keyid, profile): return True try: conn.delete_load_balancer(name) log.info('Deleted ELB %s.', name) return True except boto.exception.BotoServerError as error: log.error('Failed to delete ELB %s', name, exc_info_on_loglevel=logging.DEBUG) return False def create_listeners(name, listeners, region=None, key=None, keyid=None, profile=None): ''' Create listeners on an ELB. CLI example: .. code-block:: bash salt myminion boto_elb.create_listeners myelb '[["HTTPS", "HTTP", 443, 80, "arn:aws:iam::11 11111:server-certificate/mycert"]]' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if isinstance(listeners, six.string_types): listeners = salt.utils.json.loads(listeners) _complex_listeners = [] for listener in listeners: _complex_listeners.append(listener_dict_to_tuple(listener)) try: conn.create_load_balancer_listeners(name, [], _complex_listeners) log.info('Created ELB listeners on %s', name) return True except boto.exception.BotoServerError as error: log.error('Failed to create ELB listeners on %s: %s', name, error, exc_info_on_loglevel=logging.DEBUG) return False def delete_listeners(name, ports, region=None, key=None, keyid=None, profile=None): ''' Delete listeners on an ELB. CLI example: .. code-block:: bash salt myminion boto_elb.delete_listeners myelb '[80,443]' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if isinstance(ports, six.string_types): ports = salt.utils.json.loads(ports) try: conn.delete_load_balancer_listeners(name, ports) log.info('Deleted ELB listeners on %s', name) return True except boto.exception.BotoServerError as error: log.error('Failed to delete ELB listeners on %s: %s', name, error, exc_info_on_loglevel=logging.DEBUG) return False def apply_security_groups(name, security_groups, region=None, key=None, keyid=None, profile=None): ''' Apply security groups to ELB. CLI example: .. code-block:: bash salt myminion boto_elb.apply_security_groups myelb '["mysecgroup1"]' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if isinstance(security_groups, six.string_types): security_groups = salt.utils.json.loads(security_groups) try: conn.apply_security_groups_to_lb(name, security_groups) log.info('Applied security_groups on ELB %s', name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to appply security_groups on ELB %s: %s', name, e.message) return False def enable_availability_zones(name, availability_zones, region=None, key=None, keyid=None, profile=None): ''' Enable availability zones for ELB. CLI example: .. code-block:: bash salt myminion boto_elb.enable_availability_zones myelb '["us-east-1a"]' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if isinstance(availability_zones, six.string_types): availability_zones = salt.utils.json.loads(availability_zones) try: conn.enable_availability_zones(name, availability_zones) log.info('Enabled availability_zones on ELB %s', name) return True except boto.exception.BotoServerError as error: log.error('Failed to enable availability_zones on ELB %s: %s', name, error) return False def disable_availability_zones(name, availability_zones, region=None, key=None, keyid=None, profile=None): ''' Disable availability zones for ELB. CLI example: .. code-block:: bash salt myminion boto_elb.disable_availability_zones myelb '["us-east-1a"]' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if isinstance(availability_zones, six.string_types): availability_zones = salt.utils.json.loads(availability_zones) try: conn.disable_availability_zones(name, availability_zones) log.info('Disabled availability_zones on ELB %s', name) return True except boto.exception.BotoServerError as error: log.error('Failed to disable availability_zones on ELB %s: %s', name, error, exc_info_on_loglevel=logging.DEBUG) return False def attach_subnets(name, subnets, region=None, key=None, keyid=None, profile=None): ''' Attach ELB to subnets. CLI example: .. code-block:: bash salt myminion boto_elb.attach_subnets myelb '["mysubnet"]' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if isinstance(subnets, six.string_types): subnets = salt.utils.json.loads(subnets) try: conn.attach_lb_to_subnets(name, subnets) log.info('Attached ELB %s on subnets.', name) return True except boto.exception.BotoServerError as error: log.error('Failed to attach ELB %s on subnets: %s', name, error, exc_info_on_loglevel=logging.DEBUG) return False def detach_subnets(name, subnets, region=None, key=None, keyid=None, profile=None): ''' Detach ELB from subnets. CLI example: .. code-block:: bash salt myminion boto_elb.detach_subnets myelb '["mysubnet"]' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if isinstance(subnets, six.string_types): subnets = salt.utils.json.loads(subnets) try: conn.detach_lb_from_subnets(name, subnets) log.info('Detached ELB %s from subnets.', name) return True except boto.exception.BotoServerError as error: log.error('Failed to detach ELB %s from subnets: %s', name, error, exc_info_on_loglevel=logging.DEBUG) return False def get_attributes(name, region=None, key=None, keyid=None, profile=None): ''' Check to see if attributes are set on an ELB. CLI example: .. code-block:: bash salt myminion boto_elb.get_attributes myelb ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) retries = 30 while retries: try: lbattrs = conn.get_all_lb_attributes(name) ret = odict.OrderedDict() ret['access_log'] = odict.OrderedDict() ret['cross_zone_load_balancing'] = odict.OrderedDict() ret['connection_draining'] = odict.OrderedDict() ret['connecting_settings'] = odict.OrderedDict() al = lbattrs.access_log czlb = lbattrs.cross_zone_load_balancing cd = lbattrs.connection_draining cs = lbattrs.connecting_settings ret['access_log']['enabled'] = al.enabled ret['access_log']['s3_bucket_name'] = al.s3_bucket_name ret['access_log']['s3_bucket_prefix'] = al.s3_bucket_prefix ret['access_log']['emit_interval'] = al.emit_interval ret['cross_zone_load_balancing']['enabled'] = czlb.enabled ret['connection_draining']['enabled'] = cd.enabled ret['connection_draining']['timeout'] = cd.timeout ret['connecting_settings']['idle_timeout'] = cs.idle_timeout return ret except boto.exception.BotoServerError as e: if e.error_code == 'Throttling': log.debug("Throttled by AWS API, will retry in 5 seconds...") time.sleep(5) retries -= 1 continue log.error('ELB %s does not exist: %s', name, e.message) return {} return {} def set_attributes(name, attributes, region=None, key=None, keyid=None, profile=None): ''' Set attributes on an ELB. name (string) Name of the ELB instance to set attributes for attributes A dict of attributes to set. Valid attributes are: access_log (dict) enabled (bool) Enable storage of access logs. s3_bucket_name (string) The name of the S3 bucket to place logs. s3_bucket_prefix (string) Prefix for the log file name. emit_interval (int) Interval for storing logs in S3 in minutes. Valid values are 5 and 60. connection_draining (dict) enabled (bool) Enable connection draining. timeout (int) Maximum allowed time in seconds for sending existing connections to an instance that is deregistering or unhealthy. Default is 300. cross_zone_load_balancing (dict) enabled (bool) Enable cross-zone load balancing. CLI example to set attributes on an ELB: .. code-block:: bash salt myminion boto_elb.set_attributes myelb '{"access_log": {"enabled": "true", "s3_bucket_name": "mybucket", "s3_bucket_prefix": "mylogs/", "emit_interval": "5"}}' region=us-east-1 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) al = attributes.get('access_log', {}) czlb = attributes.get('cross_zone_load_balancing', {}) cd = attributes.get('connection_draining', {}) cs = attributes.get('connecting_settings', {}) if not al and not czlb and not cd and not cs: log.error('No supported attributes for ELB.') return False if al: _al = AccessLogAttribute() _al.enabled = al.get('enabled', False) if not _al.enabled: msg = 'Access log attribute configured, but enabled config missing' log.error(msg) return False _al.s3_bucket_name = al.get('s3_bucket_name', None) _al.s3_bucket_prefix = al.get('s3_bucket_prefix', None) _al.emit_interval = al.get('emit_interval', None) added_attr = conn.modify_lb_attribute(name, 'accessLog', _al) if added_attr: log.info('Added access_log attribute to %s elb.', name) else: log.error('Failed to add access_log attribute to %s elb.', name) return False if czlb: _czlb = CrossZoneLoadBalancingAttribute() _czlb.enabled = czlb['enabled'] added_attr = conn.modify_lb_attribute(name, 'crossZoneLoadBalancing', _czlb.enabled) if added_attr: log.info('Added cross_zone_load_balancing attribute to %s elb.', name) else: log.error('Failed to add cross_zone_load_balancing attribute.') return False if cd: _cd = ConnectionDrainingAttribute() _cd.enabled = cd['enabled'] _cd.timeout = cd.get('timeout', 300) added_attr = conn.modify_lb_attribute(name, 'connectionDraining', _cd) if added_attr: log.info('Added connection_draining attribute to %s elb.', name) else: log.error('Failed to add connection_draining attribute.') return False if cs: _cs = ConnectionSettingAttribute() _cs.idle_timeout = cs.get('idle_timeout', 60) added_attr = conn.modify_lb_attribute(name, 'connectingSettings', _cs) if added_attr: log.info('Added connecting_settings attribute to %s elb.', name) else: log.error('Failed to add connecting_settings attribute.') return False return True def get_health_check(name, region=None, key=None, keyid=None, profile=None): ''' Get the health check configured for this ELB. CLI example: .. code-block:: bash salt myminion boto_elb.get_health_check myelb ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) retries = 30 while True: try: lb = conn.get_all_load_balancers(load_balancer_names=[name]) lb = lb[0] ret = odict.OrderedDict() hc = lb.health_check ret['interval'] = hc.interval ret['target'] = hc.target ret['healthy_threshold'] = hc.healthy_threshold ret['timeout'] = hc.timeout ret['unhealthy_threshold'] = hc.unhealthy_threshold return ret except boto.exception.BotoServerError as e: if retries and e.code == 'Throttling': log.debug('Throttled by AWS API, will retry in 5 seconds.') time.sleep(5) retries -= 1 continue log.error('ELB %s not found.', name, exc_info_on_logleve=logging.DEBUG) return {} def set_health_check(name, health_check, region=None, key=None, keyid=None, profile=None): ''' Set attributes on an ELB. CLI example to set attributes on an ELB: .. code-block:: bash salt myminion boto_elb.set_health_check myelb '{"target": "HTTP:80/"}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) retries = 30 hc = HealthCheck(**health_check) while True: try: conn.configure_health_check(name, hc) log.info('Configured health check on ELB %s', name) return True except boto.exception.BotoServerError as error: if retries and e.code == 'Throttling': log.debug('Throttled by AWS API, will retry in 5 seconds.') time.sleep(5) retries -= 1 continue log.exception('Failed to configure health check on ELB %s', name) return False def register_instances(name, instances, region=None, key=None, keyid=None, profile=None): ''' Register instances with an ELB. Instances is either a string instance id or a list of string instance id's. Returns: - ``True``: instance(s) registered successfully - ``False``: instance(s) failed to be registered CLI example: .. code-block:: bash salt myminion boto_elb.register_instances myelb instance_id salt myminion boto_elb.register_instances myelb "[instance_id,instance_id]" ''' # convert instances to list type, enabling consistent use of instances # variable throughout the register_instances method if isinstance(instances, six.string_types) or isinstance(instances, six.text_type): instances = [instances] conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: registered_instances = conn.register_instances(name, instances) except boto.exception.BotoServerError as error: log.warning(error) return False registered_instance_ids = [instance.id for instance in registered_instances] # register_failues is a set that will contain any instances that were not # able to be registered with the given ELB register_failures = set(instances).difference(set(registered_instance_ids)) if register_failures: log.warning('Instance(s): %s not registered with ELB %s.', list(register_failures), name) register_result = False else: register_result = True return register_result def deregister_instances(name, instances, region=None, key=None, keyid=None, profile=None): ''' Deregister instances with an ELB. Instances is either a string instance id or a list of string instance id's. Returns: - ``True``: instance(s) deregistered successfully - ``False``: instance(s) failed to be deregistered - ``None``: instance(s) not valid or not registered, no action taken CLI example: .. code-block:: bash salt myminion boto_elb.deregister_instances myelb instance_id salt myminion boto_elb.deregister_instances myelb "[instance_id, instance_id]" ''' # convert instances to list type, enabling consistent use of instances # variable throughout the deregister_instances method if isinstance(instances, six.string_types) or isinstance(instances, six.text_type): instances = [instances] conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: registered_instances = conn.deregister_instances(name, instances) except boto.exception.BotoServerError as error: # if the instance(s) given as an argument are not members of the ELB # boto returns error.error_code == 'InvalidInstance' # deregister_instances returns "None" because the instances are # effectively deregistered from ELB if error.error_code == 'InvalidInstance': log.warning( 'One or more of instance(s) %s are not part of ELB %s. ' 'deregister_instances not performed.', instances, name ) return None else: log.warning(error) return False registered_instance_ids = [instance.id for instance in registered_instances] # deregister_failures is a set that will contain any instances that were # unable to be deregistered from the given ELB deregister_failures = set(instances).intersection(set(registered_instance_ids)) if deregister_failures: log.warning( 'Instance(s): %s not deregistered from ELB %s.', list(deregister_failures), name ) deregister_result = False else: deregister_result = True return deregister_result def set_instances(name, instances, test=False, region=None, key=None, keyid=None, profile=None): ''' Set the instances assigned to an ELB to exactly the list given CLI example: .. code-block:: bash salt myminion boto_elb.set_instances myelb region=us-east-1 instances="[instance_id,instance_id]" ''' ret = True current = set([i['instance_id'] for i in get_instance_health(name, region, key, keyid, profile)]) desired = set(instances) add = desired - current remove = current - desired if test: return bool(add or remove) if remove: if deregister_instances(name, list(remove), region, key, keyid, profile) is False: ret = False if add: if register_instances(name, list(add), region, key, keyid, profile) is False: ret = False return ret def get_instance_health(name, region=None, key=None, keyid=None, profile=None, instances=None): ''' Get a list of instances and their health state CLI example: .. code-block:: bash salt myminion boto_elb.get_instance_health myelb salt myminion boto_elb.get_instance_health myelb region=us-east-1 instances="[instance_id,instance_id]" ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: instance_states = conn.describe_instance_health(name, instances) ret = [] for _instance in instance_states: ret.append({'instance_id': _instance.instance_id, 'description': _instance.description, 'state': _instance.state, 'reason_code': _instance.reason_code }) return ret except boto.exception.BotoServerError as error: log.debug(error) return [] def create_policy(name, policy_name, policy_type, policy, region=None, key=None, keyid=None, profile=None): ''' Create an ELB policy. .. versionadded:: 2016.3.0 CLI example: .. code-block:: bash salt myminion boto_elb.create_policy myelb mypolicy LBCookieStickinessPolicyType '{"CookieExpirationPeriod": 3600}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not exists(name, region, key, keyid, profile): return False try: success = conn.create_lb_policy(name, policy_name, policy_type, policy) if success: log.info('Created policy %s on ELB %s', policy_name, name) return True else: log.error('Failed to create policy %s on ELB %s', policy_name, name) return False except boto.exception.BotoServerError as e: log.error('Failed to create policy %s on ELB %s: %s', policy_name, name, e.message, exc_info_on_loglevel=logging.DEBUG) return False def delete_policy(name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Delete an ELB policy. .. versionadded:: 2016.3.0 CLI example: .. code-block:: bash salt myminion boto_elb.delete_policy myelb mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not exists(name, region, key, keyid, profile): return True try: conn.delete_lb_policy(name, policy_name) log.info('Deleted policy %s on ELB %s', policy_name, name) return True except boto.exception.BotoServerError as e: log.error('Failed to delete policy %s on ELB %s: %s', policy_name, name, e.message, exc_info_on_loglevel=logging.DEBUG) return False def set_listener_policy(name, port, policies=None, region=None, key=None, keyid=None, profile=None): ''' Set the policies of an ELB listener. .. versionadded:: 2016.3.0 CLI example: .. code-block:: Bash salt myminion boto_elb.set_listener_policy myelb 443 "[policy1,policy2]" ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not exists(name, region, key, keyid, profile): return True if policies is None: policies = [] try: conn.set_lb_policies_of_listener(name, port, policies) log.info('Set policies %s on ELB %s listener %s', policies, name, port) except boto.exception.BotoServerError as e: log.info('Failed to set policy %s on ELB %s listener %s: %s', policies, name, port, e.message, exc_info_on_loglevel=logging.DEBUG) return False return True def set_backend_policy(name, port, policies=None, region=None, key=None, keyid=None, profile=None): ''' Set the policies of an ELB backend server. CLI example: salt myminion boto_elb.set_backend_policy myelb 443 "[policy1,policy2]" ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not exists(name, region, key, keyid, profile): return True if policies is None: policies = [] try: conn.set_lb_policies_of_backend_server(name, port, policies) log.info('Set policies %s on ELB %s backend server %s', policies, name, port) except boto.exception.BotoServerError as e: log.info('Failed to set policy %s on ELB %s backend server %s: %s', policies, name, port, e.message, exc_info_on_loglevel=logging.DEBUG) return False return True def set_tags(name, tags, region=None, key=None, keyid=None, profile=None): ''' Add the tags on an ELB .. versionadded:: 2016.3.0 name name of the ELB tags dict of name/value pair tags CLI Example: .. code-block:: bash salt myminion boto_elb.set_tags my-elb-name "{'Tag1': 'Value', 'Tag2': 'Another Value'}" ''' if exists(name, region, key, keyid, profile): conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) ret = _add_tags(conn, name, tags) return ret else: return False def _build_tag_param_list(params, tags): ''' helper function to build a tag parameter list to send ''' keys = sorted(tags.keys()) i = 1 for key in keys: value = tags[key] params['Tags.member.{0}.Key'.format(i)] = key if value is not None: params['Tags.member.{0}.Value'.format(i)] = value i += 1 def _get_all_tags(conn, load_balancer_names=None): ''' Retrieve all the metadata tags associated with your ELB(s). :type load_balancer_names: list :param load_balancer_names: An optional list of load balancer names. :rtype: list :return: A list of :class:`boto.ec2.elb.tag.Tag` objects ''' params = {} if load_balancer_names: conn.build_list_params(params, load_balancer_names, 'LoadBalancerNames.member.%d') tags = conn.get_object( 'DescribeTags', params, __utils__['boto_elb_tag.get_tag_descriptions'](), verb='POST' ) if tags[load_balancer_names]: return tags[load_balancer_names] else: return None def _add_tags(conn, load_balancer_names, tags): ''' Create new metadata tags for the specified resource ids. :type load_balancer_names: list :param load_balancer_names: A list of load balancer names. :type tags: dict :param tags: A dictionary containing the name/value pairs. If you want to create only a tag name, the value for that tag should be the empty string (e.g. ''). ''' params = {} conn.build_list_params(params, load_balancer_names, 'LoadBalancerNames.member.%d') _build_tag_param_list(params, tags) return conn.get_status('AddTags', params, verb='POST') def _remove_tags(conn, load_balancer_names, tags): ''' Delete metadata tags for the specified resource ids. :type load_balancer_names: list :param load_balancer_names: A list of load balancer names. :type tags: list :param tags: A list containing just tag names for the tags to be deleted. ''' params = {} conn.build_list_params(params, load_balancer_names, 'LoadBalancerNames.member.%d') conn.build_list_params(params, tags, 'Tags.member.%d.Key') return conn.get_status('RemoveTags', params, verb='POST')
saltstack/salt
salt/modules/boto_elb.py
_build_tag_param_list
python
def _build_tag_param_list(params, tags): ''' helper function to build a tag parameter list to send ''' keys = sorted(tags.keys()) i = 1 for key in keys: value = tags[key] params['Tags.member.{0}.Key'.format(i)] = key if value is not None: params['Tags.member.{0}.Value'.format(i)] = value i += 1
helper function to build a tag parameter list to send
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_elb.py#L1015-L1026
null
# -*- coding: utf-8 -*- ''' Connection module for Amazon ELB .. versionadded:: 2014.7.0 :configuration: This module accepts explicit elb credentials but can also utilize IAM roles assigned to the instance through Instance Profiles. Dynamic credentials are then automatically obtained from AWS API and no further configuration is necessary. More Information available at: .. code-block:: text http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/iam-roles-for-amazon-ec2.html If IAM roles are not used you need to specify them either in a pillar or in the minion's config file: .. code-block:: yaml elb.keyid: GKTADJGHEIQSXMKKRBJ08H elb.key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs A region may also be specified in the configuration: .. code-block:: yaml elb.region: us-east-1 If a region is not specified, the default is us-east-1. It's also possible to specify key, keyid and region via a profile, either as a passed in dict, or as a string to pull from pillars or minion config: .. code-block:: yaml myprofile: keyid: GKTADJGHEIQSXMKKRBJ08H key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs region: us-east-1 :depends: boto >= 2.33.0 ''' # keep lint from choking on _get_conn and _cache_id # pylint: disable=E0602 from __future__ import absolute_import, print_function, unicode_literals # Import Python libs import logging import time log = logging.getLogger(__name__) # Import Salt libs import salt.utils.json import salt.utils.odict as odict import salt.utils.versions # Import third party libs from salt.ext import six try: import boto import boto.ec2 # pylint: enable=unused-import from boto.ec2.elb import HealthCheck from boto.ec2.elb.attributes import AccessLogAttribute from boto.ec2.elb.attributes import ConnectionDrainingAttribute from boto.ec2.elb.attributes import ConnectionSettingAttribute from boto.ec2.elb.attributes import CrossZoneLoadBalancingAttribute logging.getLogger('boto').setLevel(logging.CRITICAL) HAS_BOTO = True except ImportError: HAS_BOTO = False def __virtual__(): ''' Only load if boto libraries exist. ''' # connection settings were added in 2.33.0 has_boto_reqs = salt.utils.versions.check_boto_reqs( boto_ver='2.33.0', check_boto3=False ) if has_boto_reqs is True: __utils__['boto.assign_funcs'](__name__, 'elb', module='ec2.elb', pack=__salt__) return has_boto_reqs def exists(name, region=None, key=None, keyid=None, profile=None): ''' Check to see if an ELB exists. CLI example: .. code-block:: bash salt myminion boto_elb.exists myelb region=us-east-1 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: elb = conn.get_all_load_balancers(load_balancer_names=[name]) if elb: return True else: log.debug('The load balancer does not exist in region %s', region) return False except boto.exception.BotoServerError as error: log.warning(error) return False def get_all_elbs(region=None, key=None, keyid=None, profile=None): ''' Return all load balancers associated with an account CLI example: .. code-block:: bash salt myminion boto_elb.get_all_elbs region=us-east-1 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: return [e for e in conn.get_all_load_balancers()] except boto.exception.BotoServerError as error: log.warning(error) return [] def list_elbs(region=None, key=None, keyid=None, profile=None): ''' Return names of all load balancers associated with an account CLI example: .. code-block:: bash salt myminion boto_elb.list_elbs region=us-east-1 ''' return [e.name for e in get_all_elbs(region=region, key=key, keyid=keyid, profile=profile)] def get_elb_config(name, region=None, key=None, keyid=None, profile=None): ''' Get an ELB configuration. CLI example: .. code-block:: bash salt myminion boto_elb.exists myelb region=us-east-1 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) retries = 30 while retries: try: lb = conn.get_all_load_balancers(load_balancer_names=[name]) lb = lb[0] ret = {} ret['availability_zones'] = lb.availability_zones listeners = [] for _listener in lb.listeners: listener_dict = {} listener_dict['elb_port'] = _listener.load_balancer_port listener_dict['elb_protocol'] = _listener.protocol listener_dict['instance_port'] = _listener.instance_port listener_dict['instance_protocol'] = _listener.instance_protocol listener_dict['policies'] = _listener.policy_names if _listener.ssl_certificate_id: listener_dict['certificate'] = _listener.ssl_certificate_id listeners.append(listener_dict) ret['listeners'] = listeners backends = [] for _backend in lb.backends: bs_dict = {} bs_dict['instance_port'] = _backend.instance_port bs_dict['policies'] = [p.policy_name for p in _backend.policies] backends.append(bs_dict) ret['backends'] = backends ret['subnets'] = lb.subnets ret['security_groups'] = lb.security_groups ret['scheme'] = lb.scheme ret['dns_name'] = lb.dns_name ret['tags'] = _get_all_tags(conn, name) lb_policy_lists = [ lb.policies.app_cookie_stickiness_policies, lb.policies.lb_cookie_stickiness_policies, lb.policies.other_policies ] policies = [] for policy_list in lb_policy_lists: policies += [p.policy_name for p in policy_list] ret['policies'] = policies return ret except boto.exception.BotoServerError as error: if error.error_code == 'Throttling': log.debug('Throttled by AWS API, will retry in 5 seconds.') time.sleep(5) retries -= 1 continue log.error('Error fetching config for ELB %s: %s', name, error.message) log.error(error) return {} return {} def listener_dict_to_tuple(listener): ''' Convert an ELB listener dict into a listener tuple used by certain parts of the AWS ELB API. CLI example: .. code-block:: bash salt myminion boto_elb.listener_dict_to_tuple '{"elb_port":80,"instance_port":80,"elb_protocol":"HTTP"}' ''' # We define all listeners as complex listeners. if 'instance_protocol' not in listener: instance_protocol = listener['elb_protocol'].upper() else: instance_protocol = listener['instance_protocol'].upper() listener_tuple = [listener['elb_port'], listener['instance_port'], listener['elb_protocol'], instance_protocol] if 'certificate' in listener: listener_tuple.append(listener['certificate']) return tuple(listener_tuple) def create(name, availability_zones, listeners, subnets=None, security_groups=None, scheme='internet-facing', region=None, key=None, keyid=None, profile=None): ''' Create an ELB CLI example to create an ELB: .. code-block:: bash salt myminion boto_elb.create myelb '["us-east-1a", "us-east-1e"]' '{"elb_port": 443, "elb_protocol": "HTTPS", ...}' region=us-east-1 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if exists(name, region, key, keyid, profile): return True if isinstance(availability_zones, six.string_types): availability_zones = salt.utils.json.loads(availability_zones) if isinstance(listeners, six.string_types): listeners = salt.utils.json.loads(listeners) _complex_listeners = [] for listener in listeners: _complex_listeners.append(listener_dict_to_tuple(listener)) try: lb = conn.create_load_balancer(name=name, zones=availability_zones, subnets=subnets, security_groups=security_groups, scheme=scheme, complex_listeners=_complex_listeners) if lb: log.info('Created ELB %s', name) return True else: log.error('Failed to create ELB %s', name) return False except boto.exception.BotoServerError as error: log.error('Failed to create ELB %s: %s: %s', name, error.error_code, error.message, exc_info_on_loglevel=logging.DEBUG) return False def delete(name, region=None, key=None, keyid=None, profile=None): ''' Delete an ELB. CLI example to delete an ELB: .. code-block:: bash salt myminion boto_elb.delete myelb region=us-east-1 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not exists(name, region, key, keyid, profile): return True try: conn.delete_load_balancer(name) log.info('Deleted ELB %s.', name) return True except boto.exception.BotoServerError as error: log.error('Failed to delete ELB %s', name, exc_info_on_loglevel=logging.DEBUG) return False def create_listeners(name, listeners, region=None, key=None, keyid=None, profile=None): ''' Create listeners on an ELB. CLI example: .. code-block:: bash salt myminion boto_elb.create_listeners myelb '[["HTTPS", "HTTP", 443, 80, "arn:aws:iam::11 11111:server-certificate/mycert"]]' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if isinstance(listeners, six.string_types): listeners = salt.utils.json.loads(listeners) _complex_listeners = [] for listener in listeners: _complex_listeners.append(listener_dict_to_tuple(listener)) try: conn.create_load_balancer_listeners(name, [], _complex_listeners) log.info('Created ELB listeners on %s', name) return True except boto.exception.BotoServerError as error: log.error('Failed to create ELB listeners on %s: %s', name, error, exc_info_on_loglevel=logging.DEBUG) return False def delete_listeners(name, ports, region=None, key=None, keyid=None, profile=None): ''' Delete listeners on an ELB. CLI example: .. code-block:: bash salt myminion boto_elb.delete_listeners myelb '[80,443]' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if isinstance(ports, six.string_types): ports = salt.utils.json.loads(ports) try: conn.delete_load_balancer_listeners(name, ports) log.info('Deleted ELB listeners on %s', name) return True except boto.exception.BotoServerError as error: log.error('Failed to delete ELB listeners on %s: %s', name, error, exc_info_on_loglevel=logging.DEBUG) return False def apply_security_groups(name, security_groups, region=None, key=None, keyid=None, profile=None): ''' Apply security groups to ELB. CLI example: .. code-block:: bash salt myminion boto_elb.apply_security_groups myelb '["mysecgroup1"]' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if isinstance(security_groups, six.string_types): security_groups = salt.utils.json.loads(security_groups) try: conn.apply_security_groups_to_lb(name, security_groups) log.info('Applied security_groups on ELB %s', name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to appply security_groups on ELB %s: %s', name, e.message) return False def enable_availability_zones(name, availability_zones, region=None, key=None, keyid=None, profile=None): ''' Enable availability zones for ELB. CLI example: .. code-block:: bash salt myminion boto_elb.enable_availability_zones myelb '["us-east-1a"]' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if isinstance(availability_zones, six.string_types): availability_zones = salt.utils.json.loads(availability_zones) try: conn.enable_availability_zones(name, availability_zones) log.info('Enabled availability_zones on ELB %s', name) return True except boto.exception.BotoServerError as error: log.error('Failed to enable availability_zones on ELB %s: %s', name, error) return False def disable_availability_zones(name, availability_zones, region=None, key=None, keyid=None, profile=None): ''' Disable availability zones for ELB. CLI example: .. code-block:: bash salt myminion boto_elb.disable_availability_zones myelb '["us-east-1a"]' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if isinstance(availability_zones, six.string_types): availability_zones = salt.utils.json.loads(availability_zones) try: conn.disable_availability_zones(name, availability_zones) log.info('Disabled availability_zones on ELB %s', name) return True except boto.exception.BotoServerError as error: log.error('Failed to disable availability_zones on ELB %s: %s', name, error, exc_info_on_loglevel=logging.DEBUG) return False def attach_subnets(name, subnets, region=None, key=None, keyid=None, profile=None): ''' Attach ELB to subnets. CLI example: .. code-block:: bash salt myminion boto_elb.attach_subnets myelb '["mysubnet"]' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if isinstance(subnets, six.string_types): subnets = salt.utils.json.loads(subnets) try: conn.attach_lb_to_subnets(name, subnets) log.info('Attached ELB %s on subnets.', name) return True except boto.exception.BotoServerError as error: log.error('Failed to attach ELB %s on subnets: %s', name, error, exc_info_on_loglevel=logging.DEBUG) return False def detach_subnets(name, subnets, region=None, key=None, keyid=None, profile=None): ''' Detach ELB from subnets. CLI example: .. code-block:: bash salt myminion boto_elb.detach_subnets myelb '["mysubnet"]' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if isinstance(subnets, six.string_types): subnets = salt.utils.json.loads(subnets) try: conn.detach_lb_from_subnets(name, subnets) log.info('Detached ELB %s from subnets.', name) return True except boto.exception.BotoServerError as error: log.error('Failed to detach ELB %s from subnets: %s', name, error, exc_info_on_loglevel=logging.DEBUG) return False def get_attributes(name, region=None, key=None, keyid=None, profile=None): ''' Check to see if attributes are set on an ELB. CLI example: .. code-block:: bash salt myminion boto_elb.get_attributes myelb ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) retries = 30 while retries: try: lbattrs = conn.get_all_lb_attributes(name) ret = odict.OrderedDict() ret['access_log'] = odict.OrderedDict() ret['cross_zone_load_balancing'] = odict.OrderedDict() ret['connection_draining'] = odict.OrderedDict() ret['connecting_settings'] = odict.OrderedDict() al = lbattrs.access_log czlb = lbattrs.cross_zone_load_balancing cd = lbattrs.connection_draining cs = lbattrs.connecting_settings ret['access_log']['enabled'] = al.enabled ret['access_log']['s3_bucket_name'] = al.s3_bucket_name ret['access_log']['s3_bucket_prefix'] = al.s3_bucket_prefix ret['access_log']['emit_interval'] = al.emit_interval ret['cross_zone_load_balancing']['enabled'] = czlb.enabled ret['connection_draining']['enabled'] = cd.enabled ret['connection_draining']['timeout'] = cd.timeout ret['connecting_settings']['idle_timeout'] = cs.idle_timeout return ret except boto.exception.BotoServerError as e: if e.error_code == 'Throttling': log.debug("Throttled by AWS API, will retry in 5 seconds...") time.sleep(5) retries -= 1 continue log.error('ELB %s does not exist: %s', name, e.message) return {} return {} def set_attributes(name, attributes, region=None, key=None, keyid=None, profile=None): ''' Set attributes on an ELB. name (string) Name of the ELB instance to set attributes for attributes A dict of attributes to set. Valid attributes are: access_log (dict) enabled (bool) Enable storage of access logs. s3_bucket_name (string) The name of the S3 bucket to place logs. s3_bucket_prefix (string) Prefix for the log file name. emit_interval (int) Interval for storing logs in S3 in minutes. Valid values are 5 and 60. connection_draining (dict) enabled (bool) Enable connection draining. timeout (int) Maximum allowed time in seconds for sending existing connections to an instance that is deregistering or unhealthy. Default is 300. cross_zone_load_balancing (dict) enabled (bool) Enable cross-zone load balancing. CLI example to set attributes on an ELB: .. code-block:: bash salt myminion boto_elb.set_attributes myelb '{"access_log": {"enabled": "true", "s3_bucket_name": "mybucket", "s3_bucket_prefix": "mylogs/", "emit_interval": "5"}}' region=us-east-1 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) al = attributes.get('access_log', {}) czlb = attributes.get('cross_zone_load_balancing', {}) cd = attributes.get('connection_draining', {}) cs = attributes.get('connecting_settings', {}) if not al and not czlb and not cd and not cs: log.error('No supported attributes for ELB.') return False if al: _al = AccessLogAttribute() _al.enabled = al.get('enabled', False) if not _al.enabled: msg = 'Access log attribute configured, but enabled config missing' log.error(msg) return False _al.s3_bucket_name = al.get('s3_bucket_name', None) _al.s3_bucket_prefix = al.get('s3_bucket_prefix', None) _al.emit_interval = al.get('emit_interval', None) added_attr = conn.modify_lb_attribute(name, 'accessLog', _al) if added_attr: log.info('Added access_log attribute to %s elb.', name) else: log.error('Failed to add access_log attribute to %s elb.', name) return False if czlb: _czlb = CrossZoneLoadBalancingAttribute() _czlb.enabled = czlb['enabled'] added_attr = conn.modify_lb_attribute(name, 'crossZoneLoadBalancing', _czlb.enabled) if added_attr: log.info('Added cross_zone_load_balancing attribute to %s elb.', name) else: log.error('Failed to add cross_zone_load_balancing attribute.') return False if cd: _cd = ConnectionDrainingAttribute() _cd.enabled = cd['enabled'] _cd.timeout = cd.get('timeout', 300) added_attr = conn.modify_lb_attribute(name, 'connectionDraining', _cd) if added_attr: log.info('Added connection_draining attribute to %s elb.', name) else: log.error('Failed to add connection_draining attribute.') return False if cs: _cs = ConnectionSettingAttribute() _cs.idle_timeout = cs.get('idle_timeout', 60) added_attr = conn.modify_lb_attribute(name, 'connectingSettings', _cs) if added_attr: log.info('Added connecting_settings attribute to %s elb.', name) else: log.error('Failed to add connecting_settings attribute.') return False return True def get_health_check(name, region=None, key=None, keyid=None, profile=None): ''' Get the health check configured for this ELB. CLI example: .. code-block:: bash salt myminion boto_elb.get_health_check myelb ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) retries = 30 while True: try: lb = conn.get_all_load_balancers(load_balancer_names=[name]) lb = lb[0] ret = odict.OrderedDict() hc = lb.health_check ret['interval'] = hc.interval ret['target'] = hc.target ret['healthy_threshold'] = hc.healthy_threshold ret['timeout'] = hc.timeout ret['unhealthy_threshold'] = hc.unhealthy_threshold return ret except boto.exception.BotoServerError as e: if retries and e.code == 'Throttling': log.debug('Throttled by AWS API, will retry in 5 seconds.') time.sleep(5) retries -= 1 continue log.error('ELB %s not found.', name, exc_info_on_logleve=logging.DEBUG) return {} def set_health_check(name, health_check, region=None, key=None, keyid=None, profile=None): ''' Set attributes on an ELB. CLI example to set attributes on an ELB: .. code-block:: bash salt myminion boto_elb.set_health_check myelb '{"target": "HTTP:80/"}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) retries = 30 hc = HealthCheck(**health_check) while True: try: conn.configure_health_check(name, hc) log.info('Configured health check on ELB %s', name) return True except boto.exception.BotoServerError as error: if retries and e.code == 'Throttling': log.debug('Throttled by AWS API, will retry in 5 seconds.') time.sleep(5) retries -= 1 continue log.exception('Failed to configure health check on ELB %s', name) return False def register_instances(name, instances, region=None, key=None, keyid=None, profile=None): ''' Register instances with an ELB. Instances is either a string instance id or a list of string instance id's. Returns: - ``True``: instance(s) registered successfully - ``False``: instance(s) failed to be registered CLI example: .. code-block:: bash salt myminion boto_elb.register_instances myelb instance_id salt myminion boto_elb.register_instances myelb "[instance_id,instance_id]" ''' # convert instances to list type, enabling consistent use of instances # variable throughout the register_instances method if isinstance(instances, six.string_types) or isinstance(instances, six.text_type): instances = [instances] conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: registered_instances = conn.register_instances(name, instances) except boto.exception.BotoServerError as error: log.warning(error) return False registered_instance_ids = [instance.id for instance in registered_instances] # register_failues is a set that will contain any instances that were not # able to be registered with the given ELB register_failures = set(instances).difference(set(registered_instance_ids)) if register_failures: log.warning('Instance(s): %s not registered with ELB %s.', list(register_failures), name) register_result = False else: register_result = True return register_result def deregister_instances(name, instances, region=None, key=None, keyid=None, profile=None): ''' Deregister instances with an ELB. Instances is either a string instance id or a list of string instance id's. Returns: - ``True``: instance(s) deregistered successfully - ``False``: instance(s) failed to be deregistered - ``None``: instance(s) not valid or not registered, no action taken CLI example: .. code-block:: bash salt myminion boto_elb.deregister_instances myelb instance_id salt myminion boto_elb.deregister_instances myelb "[instance_id, instance_id]" ''' # convert instances to list type, enabling consistent use of instances # variable throughout the deregister_instances method if isinstance(instances, six.string_types) or isinstance(instances, six.text_type): instances = [instances] conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: registered_instances = conn.deregister_instances(name, instances) except boto.exception.BotoServerError as error: # if the instance(s) given as an argument are not members of the ELB # boto returns error.error_code == 'InvalidInstance' # deregister_instances returns "None" because the instances are # effectively deregistered from ELB if error.error_code == 'InvalidInstance': log.warning( 'One or more of instance(s) %s are not part of ELB %s. ' 'deregister_instances not performed.', instances, name ) return None else: log.warning(error) return False registered_instance_ids = [instance.id for instance in registered_instances] # deregister_failures is a set that will contain any instances that were # unable to be deregistered from the given ELB deregister_failures = set(instances).intersection(set(registered_instance_ids)) if deregister_failures: log.warning( 'Instance(s): %s not deregistered from ELB %s.', list(deregister_failures), name ) deregister_result = False else: deregister_result = True return deregister_result def set_instances(name, instances, test=False, region=None, key=None, keyid=None, profile=None): ''' Set the instances assigned to an ELB to exactly the list given CLI example: .. code-block:: bash salt myminion boto_elb.set_instances myelb region=us-east-1 instances="[instance_id,instance_id]" ''' ret = True current = set([i['instance_id'] for i in get_instance_health(name, region, key, keyid, profile)]) desired = set(instances) add = desired - current remove = current - desired if test: return bool(add or remove) if remove: if deregister_instances(name, list(remove), region, key, keyid, profile) is False: ret = False if add: if register_instances(name, list(add), region, key, keyid, profile) is False: ret = False return ret def get_instance_health(name, region=None, key=None, keyid=None, profile=None, instances=None): ''' Get a list of instances and their health state CLI example: .. code-block:: bash salt myminion boto_elb.get_instance_health myelb salt myminion boto_elb.get_instance_health myelb region=us-east-1 instances="[instance_id,instance_id]" ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: instance_states = conn.describe_instance_health(name, instances) ret = [] for _instance in instance_states: ret.append({'instance_id': _instance.instance_id, 'description': _instance.description, 'state': _instance.state, 'reason_code': _instance.reason_code }) return ret except boto.exception.BotoServerError as error: log.debug(error) return [] def create_policy(name, policy_name, policy_type, policy, region=None, key=None, keyid=None, profile=None): ''' Create an ELB policy. .. versionadded:: 2016.3.0 CLI example: .. code-block:: bash salt myminion boto_elb.create_policy myelb mypolicy LBCookieStickinessPolicyType '{"CookieExpirationPeriod": 3600}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not exists(name, region, key, keyid, profile): return False try: success = conn.create_lb_policy(name, policy_name, policy_type, policy) if success: log.info('Created policy %s on ELB %s', policy_name, name) return True else: log.error('Failed to create policy %s on ELB %s', policy_name, name) return False except boto.exception.BotoServerError as e: log.error('Failed to create policy %s on ELB %s: %s', policy_name, name, e.message, exc_info_on_loglevel=logging.DEBUG) return False def delete_policy(name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Delete an ELB policy. .. versionadded:: 2016.3.0 CLI example: .. code-block:: bash salt myminion boto_elb.delete_policy myelb mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not exists(name, region, key, keyid, profile): return True try: conn.delete_lb_policy(name, policy_name) log.info('Deleted policy %s on ELB %s', policy_name, name) return True except boto.exception.BotoServerError as e: log.error('Failed to delete policy %s on ELB %s: %s', policy_name, name, e.message, exc_info_on_loglevel=logging.DEBUG) return False def set_listener_policy(name, port, policies=None, region=None, key=None, keyid=None, profile=None): ''' Set the policies of an ELB listener. .. versionadded:: 2016.3.0 CLI example: .. code-block:: Bash salt myminion boto_elb.set_listener_policy myelb 443 "[policy1,policy2]" ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not exists(name, region, key, keyid, profile): return True if policies is None: policies = [] try: conn.set_lb_policies_of_listener(name, port, policies) log.info('Set policies %s on ELB %s listener %s', policies, name, port) except boto.exception.BotoServerError as e: log.info('Failed to set policy %s on ELB %s listener %s: %s', policies, name, port, e.message, exc_info_on_loglevel=logging.DEBUG) return False return True def set_backend_policy(name, port, policies=None, region=None, key=None, keyid=None, profile=None): ''' Set the policies of an ELB backend server. CLI example: salt myminion boto_elb.set_backend_policy myelb 443 "[policy1,policy2]" ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not exists(name, region, key, keyid, profile): return True if policies is None: policies = [] try: conn.set_lb_policies_of_backend_server(name, port, policies) log.info('Set policies %s on ELB %s backend server %s', policies, name, port) except boto.exception.BotoServerError as e: log.info('Failed to set policy %s on ELB %s backend server %s: %s', policies, name, port, e.message, exc_info_on_loglevel=logging.DEBUG) return False return True def set_tags(name, tags, region=None, key=None, keyid=None, profile=None): ''' Add the tags on an ELB .. versionadded:: 2016.3.0 name name of the ELB tags dict of name/value pair tags CLI Example: .. code-block:: bash salt myminion boto_elb.set_tags my-elb-name "{'Tag1': 'Value', 'Tag2': 'Another Value'}" ''' if exists(name, region, key, keyid, profile): conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) ret = _add_tags(conn, name, tags) return ret else: return False def delete_tags(name, tags, region=None, key=None, keyid=None, profile=None): ''' Add the tags on an ELB name name of the ELB tags list of tags to remove CLI Example: .. code-block:: bash salt myminion boto_elb.delete_tags my-elb-name ['TagToRemove1', 'TagToRemove2'] ''' if exists(name, region, key, keyid, profile): conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) ret = _remove_tags(conn, name, tags) return ret else: return False def _get_all_tags(conn, load_balancer_names=None): ''' Retrieve all the metadata tags associated with your ELB(s). :type load_balancer_names: list :param load_balancer_names: An optional list of load balancer names. :rtype: list :return: A list of :class:`boto.ec2.elb.tag.Tag` objects ''' params = {} if load_balancer_names: conn.build_list_params(params, load_balancer_names, 'LoadBalancerNames.member.%d') tags = conn.get_object( 'DescribeTags', params, __utils__['boto_elb_tag.get_tag_descriptions'](), verb='POST' ) if tags[load_balancer_names]: return tags[load_balancer_names] else: return None def _add_tags(conn, load_balancer_names, tags): ''' Create new metadata tags for the specified resource ids. :type load_balancer_names: list :param load_balancer_names: A list of load balancer names. :type tags: dict :param tags: A dictionary containing the name/value pairs. If you want to create only a tag name, the value for that tag should be the empty string (e.g. ''). ''' params = {} conn.build_list_params(params, load_balancer_names, 'LoadBalancerNames.member.%d') _build_tag_param_list(params, tags) return conn.get_status('AddTags', params, verb='POST') def _remove_tags(conn, load_balancer_names, tags): ''' Delete metadata tags for the specified resource ids. :type load_balancer_names: list :param load_balancer_names: A list of load balancer names. :type tags: list :param tags: A list containing just tag names for the tags to be deleted. ''' params = {} conn.build_list_params(params, load_balancer_names, 'LoadBalancerNames.member.%d') conn.build_list_params(params, tags, 'Tags.member.%d.Key') return conn.get_status('RemoveTags', params, verb='POST')
saltstack/salt
salt/modules/boto_elb.py
_get_all_tags
python
def _get_all_tags(conn, load_balancer_names=None): ''' Retrieve all the metadata tags associated with your ELB(s). :type load_balancer_names: list :param load_balancer_names: An optional list of load balancer names. :rtype: list :return: A list of :class:`boto.ec2.elb.tag.Tag` objects ''' params = {} if load_balancer_names: conn.build_list_params(params, load_balancer_names, 'LoadBalancerNames.member.%d') tags = conn.get_object( 'DescribeTags', params, __utils__['boto_elb_tag.get_tag_descriptions'](), verb='POST' ) if tags[load_balancer_names]: return tags[load_balancer_names] else: return None
Retrieve all the metadata tags associated with your ELB(s). :type load_balancer_names: list :param load_balancer_names: An optional list of load balancer names. :rtype: list :return: A list of :class:`boto.ec2.elb.tag.Tag` objects
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_elb.py#L1029-L1053
null
# -*- coding: utf-8 -*- ''' Connection module for Amazon ELB .. versionadded:: 2014.7.0 :configuration: This module accepts explicit elb credentials but can also utilize IAM roles assigned to the instance through Instance Profiles. Dynamic credentials are then automatically obtained from AWS API and no further configuration is necessary. More Information available at: .. code-block:: text http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/iam-roles-for-amazon-ec2.html If IAM roles are not used you need to specify them either in a pillar or in the minion's config file: .. code-block:: yaml elb.keyid: GKTADJGHEIQSXMKKRBJ08H elb.key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs A region may also be specified in the configuration: .. code-block:: yaml elb.region: us-east-1 If a region is not specified, the default is us-east-1. It's also possible to specify key, keyid and region via a profile, either as a passed in dict, or as a string to pull from pillars or minion config: .. code-block:: yaml myprofile: keyid: GKTADJGHEIQSXMKKRBJ08H key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs region: us-east-1 :depends: boto >= 2.33.0 ''' # keep lint from choking on _get_conn and _cache_id # pylint: disable=E0602 from __future__ import absolute_import, print_function, unicode_literals # Import Python libs import logging import time log = logging.getLogger(__name__) # Import Salt libs import salt.utils.json import salt.utils.odict as odict import salt.utils.versions # Import third party libs from salt.ext import six try: import boto import boto.ec2 # pylint: enable=unused-import from boto.ec2.elb import HealthCheck from boto.ec2.elb.attributes import AccessLogAttribute from boto.ec2.elb.attributes import ConnectionDrainingAttribute from boto.ec2.elb.attributes import ConnectionSettingAttribute from boto.ec2.elb.attributes import CrossZoneLoadBalancingAttribute logging.getLogger('boto').setLevel(logging.CRITICAL) HAS_BOTO = True except ImportError: HAS_BOTO = False def __virtual__(): ''' Only load if boto libraries exist. ''' # connection settings were added in 2.33.0 has_boto_reqs = salt.utils.versions.check_boto_reqs( boto_ver='2.33.0', check_boto3=False ) if has_boto_reqs is True: __utils__['boto.assign_funcs'](__name__, 'elb', module='ec2.elb', pack=__salt__) return has_boto_reqs def exists(name, region=None, key=None, keyid=None, profile=None): ''' Check to see if an ELB exists. CLI example: .. code-block:: bash salt myminion boto_elb.exists myelb region=us-east-1 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: elb = conn.get_all_load_balancers(load_balancer_names=[name]) if elb: return True else: log.debug('The load balancer does not exist in region %s', region) return False except boto.exception.BotoServerError as error: log.warning(error) return False def get_all_elbs(region=None, key=None, keyid=None, profile=None): ''' Return all load balancers associated with an account CLI example: .. code-block:: bash salt myminion boto_elb.get_all_elbs region=us-east-1 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: return [e for e in conn.get_all_load_balancers()] except boto.exception.BotoServerError as error: log.warning(error) return [] def list_elbs(region=None, key=None, keyid=None, profile=None): ''' Return names of all load balancers associated with an account CLI example: .. code-block:: bash salt myminion boto_elb.list_elbs region=us-east-1 ''' return [e.name for e in get_all_elbs(region=region, key=key, keyid=keyid, profile=profile)] def get_elb_config(name, region=None, key=None, keyid=None, profile=None): ''' Get an ELB configuration. CLI example: .. code-block:: bash salt myminion boto_elb.exists myelb region=us-east-1 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) retries = 30 while retries: try: lb = conn.get_all_load_balancers(load_balancer_names=[name]) lb = lb[0] ret = {} ret['availability_zones'] = lb.availability_zones listeners = [] for _listener in lb.listeners: listener_dict = {} listener_dict['elb_port'] = _listener.load_balancer_port listener_dict['elb_protocol'] = _listener.protocol listener_dict['instance_port'] = _listener.instance_port listener_dict['instance_protocol'] = _listener.instance_protocol listener_dict['policies'] = _listener.policy_names if _listener.ssl_certificate_id: listener_dict['certificate'] = _listener.ssl_certificate_id listeners.append(listener_dict) ret['listeners'] = listeners backends = [] for _backend in lb.backends: bs_dict = {} bs_dict['instance_port'] = _backend.instance_port bs_dict['policies'] = [p.policy_name for p in _backend.policies] backends.append(bs_dict) ret['backends'] = backends ret['subnets'] = lb.subnets ret['security_groups'] = lb.security_groups ret['scheme'] = lb.scheme ret['dns_name'] = lb.dns_name ret['tags'] = _get_all_tags(conn, name) lb_policy_lists = [ lb.policies.app_cookie_stickiness_policies, lb.policies.lb_cookie_stickiness_policies, lb.policies.other_policies ] policies = [] for policy_list in lb_policy_lists: policies += [p.policy_name for p in policy_list] ret['policies'] = policies return ret except boto.exception.BotoServerError as error: if error.error_code == 'Throttling': log.debug('Throttled by AWS API, will retry in 5 seconds.') time.sleep(5) retries -= 1 continue log.error('Error fetching config for ELB %s: %s', name, error.message) log.error(error) return {} return {} def listener_dict_to_tuple(listener): ''' Convert an ELB listener dict into a listener tuple used by certain parts of the AWS ELB API. CLI example: .. code-block:: bash salt myminion boto_elb.listener_dict_to_tuple '{"elb_port":80,"instance_port":80,"elb_protocol":"HTTP"}' ''' # We define all listeners as complex listeners. if 'instance_protocol' not in listener: instance_protocol = listener['elb_protocol'].upper() else: instance_protocol = listener['instance_protocol'].upper() listener_tuple = [listener['elb_port'], listener['instance_port'], listener['elb_protocol'], instance_protocol] if 'certificate' in listener: listener_tuple.append(listener['certificate']) return tuple(listener_tuple) def create(name, availability_zones, listeners, subnets=None, security_groups=None, scheme='internet-facing', region=None, key=None, keyid=None, profile=None): ''' Create an ELB CLI example to create an ELB: .. code-block:: bash salt myminion boto_elb.create myelb '["us-east-1a", "us-east-1e"]' '{"elb_port": 443, "elb_protocol": "HTTPS", ...}' region=us-east-1 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if exists(name, region, key, keyid, profile): return True if isinstance(availability_zones, six.string_types): availability_zones = salt.utils.json.loads(availability_zones) if isinstance(listeners, six.string_types): listeners = salt.utils.json.loads(listeners) _complex_listeners = [] for listener in listeners: _complex_listeners.append(listener_dict_to_tuple(listener)) try: lb = conn.create_load_balancer(name=name, zones=availability_zones, subnets=subnets, security_groups=security_groups, scheme=scheme, complex_listeners=_complex_listeners) if lb: log.info('Created ELB %s', name) return True else: log.error('Failed to create ELB %s', name) return False except boto.exception.BotoServerError as error: log.error('Failed to create ELB %s: %s: %s', name, error.error_code, error.message, exc_info_on_loglevel=logging.DEBUG) return False def delete(name, region=None, key=None, keyid=None, profile=None): ''' Delete an ELB. CLI example to delete an ELB: .. code-block:: bash salt myminion boto_elb.delete myelb region=us-east-1 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not exists(name, region, key, keyid, profile): return True try: conn.delete_load_balancer(name) log.info('Deleted ELB %s.', name) return True except boto.exception.BotoServerError as error: log.error('Failed to delete ELB %s', name, exc_info_on_loglevel=logging.DEBUG) return False def create_listeners(name, listeners, region=None, key=None, keyid=None, profile=None): ''' Create listeners on an ELB. CLI example: .. code-block:: bash salt myminion boto_elb.create_listeners myelb '[["HTTPS", "HTTP", 443, 80, "arn:aws:iam::11 11111:server-certificate/mycert"]]' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if isinstance(listeners, six.string_types): listeners = salt.utils.json.loads(listeners) _complex_listeners = [] for listener in listeners: _complex_listeners.append(listener_dict_to_tuple(listener)) try: conn.create_load_balancer_listeners(name, [], _complex_listeners) log.info('Created ELB listeners on %s', name) return True except boto.exception.BotoServerError as error: log.error('Failed to create ELB listeners on %s: %s', name, error, exc_info_on_loglevel=logging.DEBUG) return False def delete_listeners(name, ports, region=None, key=None, keyid=None, profile=None): ''' Delete listeners on an ELB. CLI example: .. code-block:: bash salt myminion boto_elb.delete_listeners myelb '[80,443]' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if isinstance(ports, six.string_types): ports = salt.utils.json.loads(ports) try: conn.delete_load_balancer_listeners(name, ports) log.info('Deleted ELB listeners on %s', name) return True except boto.exception.BotoServerError as error: log.error('Failed to delete ELB listeners on %s: %s', name, error, exc_info_on_loglevel=logging.DEBUG) return False def apply_security_groups(name, security_groups, region=None, key=None, keyid=None, profile=None): ''' Apply security groups to ELB. CLI example: .. code-block:: bash salt myminion boto_elb.apply_security_groups myelb '["mysecgroup1"]' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if isinstance(security_groups, six.string_types): security_groups = salt.utils.json.loads(security_groups) try: conn.apply_security_groups_to_lb(name, security_groups) log.info('Applied security_groups on ELB %s', name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to appply security_groups on ELB %s: %s', name, e.message) return False def enable_availability_zones(name, availability_zones, region=None, key=None, keyid=None, profile=None): ''' Enable availability zones for ELB. CLI example: .. code-block:: bash salt myminion boto_elb.enable_availability_zones myelb '["us-east-1a"]' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if isinstance(availability_zones, six.string_types): availability_zones = salt.utils.json.loads(availability_zones) try: conn.enable_availability_zones(name, availability_zones) log.info('Enabled availability_zones on ELB %s', name) return True except boto.exception.BotoServerError as error: log.error('Failed to enable availability_zones on ELB %s: %s', name, error) return False def disable_availability_zones(name, availability_zones, region=None, key=None, keyid=None, profile=None): ''' Disable availability zones for ELB. CLI example: .. code-block:: bash salt myminion boto_elb.disable_availability_zones myelb '["us-east-1a"]' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if isinstance(availability_zones, six.string_types): availability_zones = salt.utils.json.loads(availability_zones) try: conn.disable_availability_zones(name, availability_zones) log.info('Disabled availability_zones on ELB %s', name) return True except boto.exception.BotoServerError as error: log.error('Failed to disable availability_zones on ELB %s: %s', name, error, exc_info_on_loglevel=logging.DEBUG) return False def attach_subnets(name, subnets, region=None, key=None, keyid=None, profile=None): ''' Attach ELB to subnets. CLI example: .. code-block:: bash salt myminion boto_elb.attach_subnets myelb '["mysubnet"]' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if isinstance(subnets, six.string_types): subnets = salt.utils.json.loads(subnets) try: conn.attach_lb_to_subnets(name, subnets) log.info('Attached ELB %s on subnets.', name) return True except boto.exception.BotoServerError as error: log.error('Failed to attach ELB %s on subnets: %s', name, error, exc_info_on_loglevel=logging.DEBUG) return False def detach_subnets(name, subnets, region=None, key=None, keyid=None, profile=None): ''' Detach ELB from subnets. CLI example: .. code-block:: bash salt myminion boto_elb.detach_subnets myelb '["mysubnet"]' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if isinstance(subnets, six.string_types): subnets = salt.utils.json.loads(subnets) try: conn.detach_lb_from_subnets(name, subnets) log.info('Detached ELB %s from subnets.', name) return True except boto.exception.BotoServerError as error: log.error('Failed to detach ELB %s from subnets: %s', name, error, exc_info_on_loglevel=logging.DEBUG) return False def get_attributes(name, region=None, key=None, keyid=None, profile=None): ''' Check to see if attributes are set on an ELB. CLI example: .. code-block:: bash salt myminion boto_elb.get_attributes myelb ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) retries = 30 while retries: try: lbattrs = conn.get_all_lb_attributes(name) ret = odict.OrderedDict() ret['access_log'] = odict.OrderedDict() ret['cross_zone_load_balancing'] = odict.OrderedDict() ret['connection_draining'] = odict.OrderedDict() ret['connecting_settings'] = odict.OrderedDict() al = lbattrs.access_log czlb = lbattrs.cross_zone_load_balancing cd = lbattrs.connection_draining cs = lbattrs.connecting_settings ret['access_log']['enabled'] = al.enabled ret['access_log']['s3_bucket_name'] = al.s3_bucket_name ret['access_log']['s3_bucket_prefix'] = al.s3_bucket_prefix ret['access_log']['emit_interval'] = al.emit_interval ret['cross_zone_load_balancing']['enabled'] = czlb.enabled ret['connection_draining']['enabled'] = cd.enabled ret['connection_draining']['timeout'] = cd.timeout ret['connecting_settings']['idle_timeout'] = cs.idle_timeout return ret except boto.exception.BotoServerError as e: if e.error_code == 'Throttling': log.debug("Throttled by AWS API, will retry in 5 seconds...") time.sleep(5) retries -= 1 continue log.error('ELB %s does not exist: %s', name, e.message) return {} return {} def set_attributes(name, attributes, region=None, key=None, keyid=None, profile=None): ''' Set attributes on an ELB. name (string) Name of the ELB instance to set attributes for attributes A dict of attributes to set. Valid attributes are: access_log (dict) enabled (bool) Enable storage of access logs. s3_bucket_name (string) The name of the S3 bucket to place logs. s3_bucket_prefix (string) Prefix for the log file name. emit_interval (int) Interval for storing logs in S3 in minutes. Valid values are 5 and 60. connection_draining (dict) enabled (bool) Enable connection draining. timeout (int) Maximum allowed time in seconds for sending existing connections to an instance that is deregistering or unhealthy. Default is 300. cross_zone_load_balancing (dict) enabled (bool) Enable cross-zone load balancing. CLI example to set attributes on an ELB: .. code-block:: bash salt myminion boto_elb.set_attributes myelb '{"access_log": {"enabled": "true", "s3_bucket_name": "mybucket", "s3_bucket_prefix": "mylogs/", "emit_interval": "5"}}' region=us-east-1 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) al = attributes.get('access_log', {}) czlb = attributes.get('cross_zone_load_balancing', {}) cd = attributes.get('connection_draining', {}) cs = attributes.get('connecting_settings', {}) if not al and not czlb and not cd and not cs: log.error('No supported attributes for ELB.') return False if al: _al = AccessLogAttribute() _al.enabled = al.get('enabled', False) if not _al.enabled: msg = 'Access log attribute configured, but enabled config missing' log.error(msg) return False _al.s3_bucket_name = al.get('s3_bucket_name', None) _al.s3_bucket_prefix = al.get('s3_bucket_prefix', None) _al.emit_interval = al.get('emit_interval', None) added_attr = conn.modify_lb_attribute(name, 'accessLog', _al) if added_attr: log.info('Added access_log attribute to %s elb.', name) else: log.error('Failed to add access_log attribute to %s elb.', name) return False if czlb: _czlb = CrossZoneLoadBalancingAttribute() _czlb.enabled = czlb['enabled'] added_attr = conn.modify_lb_attribute(name, 'crossZoneLoadBalancing', _czlb.enabled) if added_attr: log.info('Added cross_zone_load_balancing attribute to %s elb.', name) else: log.error('Failed to add cross_zone_load_balancing attribute.') return False if cd: _cd = ConnectionDrainingAttribute() _cd.enabled = cd['enabled'] _cd.timeout = cd.get('timeout', 300) added_attr = conn.modify_lb_attribute(name, 'connectionDraining', _cd) if added_attr: log.info('Added connection_draining attribute to %s elb.', name) else: log.error('Failed to add connection_draining attribute.') return False if cs: _cs = ConnectionSettingAttribute() _cs.idle_timeout = cs.get('idle_timeout', 60) added_attr = conn.modify_lb_attribute(name, 'connectingSettings', _cs) if added_attr: log.info('Added connecting_settings attribute to %s elb.', name) else: log.error('Failed to add connecting_settings attribute.') return False return True def get_health_check(name, region=None, key=None, keyid=None, profile=None): ''' Get the health check configured for this ELB. CLI example: .. code-block:: bash salt myminion boto_elb.get_health_check myelb ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) retries = 30 while True: try: lb = conn.get_all_load_balancers(load_balancer_names=[name]) lb = lb[0] ret = odict.OrderedDict() hc = lb.health_check ret['interval'] = hc.interval ret['target'] = hc.target ret['healthy_threshold'] = hc.healthy_threshold ret['timeout'] = hc.timeout ret['unhealthy_threshold'] = hc.unhealthy_threshold return ret except boto.exception.BotoServerError as e: if retries and e.code == 'Throttling': log.debug('Throttled by AWS API, will retry in 5 seconds.') time.sleep(5) retries -= 1 continue log.error('ELB %s not found.', name, exc_info_on_logleve=logging.DEBUG) return {} def set_health_check(name, health_check, region=None, key=None, keyid=None, profile=None): ''' Set attributes on an ELB. CLI example to set attributes on an ELB: .. code-block:: bash salt myminion boto_elb.set_health_check myelb '{"target": "HTTP:80/"}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) retries = 30 hc = HealthCheck(**health_check) while True: try: conn.configure_health_check(name, hc) log.info('Configured health check on ELB %s', name) return True except boto.exception.BotoServerError as error: if retries and e.code == 'Throttling': log.debug('Throttled by AWS API, will retry in 5 seconds.') time.sleep(5) retries -= 1 continue log.exception('Failed to configure health check on ELB %s', name) return False def register_instances(name, instances, region=None, key=None, keyid=None, profile=None): ''' Register instances with an ELB. Instances is either a string instance id or a list of string instance id's. Returns: - ``True``: instance(s) registered successfully - ``False``: instance(s) failed to be registered CLI example: .. code-block:: bash salt myminion boto_elb.register_instances myelb instance_id salt myminion boto_elb.register_instances myelb "[instance_id,instance_id]" ''' # convert instances to list type, enabling consistent use of instances # variable throughout the register_instances method if isinstance(instances, six.string_types) or isinstance(instances, six.text_type): instances = [instances] conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: registered_instances = conn.register_instances(name, instances) except boto.exception.BotoServerError as error: log.warning(error) return False registered_instance_ids = [instance.id for instance in registered_instances] # register_failues is a set that will contain any instances that were not # able to be registered with the given ELB register_failures = set(instances).difference(set(registered_instance_ids)) if register_failures: log.warning('Instance(s): %s not registered with ELB %s.', list(register_failures), name) register_result = False else: register_result = True return register_result def deregister_instances(name, instances, region=None, key=None, keyid=None, profile=None): ''' Deregister instances with an ELB. Instances is either a string instance id or a list of string instance id's. Returns: - ``True``: instance(s) deregistered successfully - ``False``: instance(s) failed to be deregistered - ``None``: instance(s) not valid or not registered, no action taken CLI example: .. code-block:: bash salt myminion boto_elb.deregister_instances myelb instance_id salt myminion boto_elb.deregister_instances myelb "[instance_id, instance_id]" ''' # convert instances to list type, enabling consistent use of instances # variable throughout the deregister_instances method if isinstance(instances, six.string_types) or isinstance(instances, six.text_type): instances = [instances] conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: registered_instances = conn.deregister_instances(name, instances) except boto.exception.BotoServerError as error: # if the instance(s) given as an argument are not members of the ELB # boto returns error.error_code == 'InvalidInstance' # deregister_instances returns "None" because the instances are # effectively deregistered from ELB if error.error_code == 'InvalidInstance': log.warning( 'One or more of instance(s) %s are not part of ELB %s. ' 'deregister_instances not performed.', instances, name ) return None else: log.warning(error) return False registered_instance_ids = [instance.id for instance in registered_instances] # deregister_failures is a set that will contain any instances that were # unable to be deregistered from the given ELB deregister_failures = set(instances).intersection(set(registered_instance_ids)) if deregister_failures: log.warning( 'Instance(s): %s not deregistered from ELB %s.', list(deregister_failures), name ) deregister_result = False else: deregister_result = True return deregister_result def set_instances(name, instances, test=False, region=None, key=None, keyid=None, profile=None): ''' Set the instances assigned to an ELB to exactly the list given CLI example: .. code-block:: bash salt myminion boto_elb.set_instances myelb region=us-east-1 instances="[instance_id,instance_id]" ''' ret = True current = set([i['instance_id'] for i in get_instance_health(name, region, key, keyid, profile)]) desired = set(instances) add = desired - current remove = current - desired if test: return bool(add or remove) if remove: if deregister_instances(name, list(remove), region, key, keyid, profile) is False: ret = False if add: if register_instances(name, list(add), region, key, keyid, profile) is False: ret = False return ret def get_instance_health(name, region=None, key=None, keyid=None, profile=None, instances=None): ''' Get a list of instances and their health state CLI example: .. code-block:: bash salt myminion boto_elb.get_instance_health myelb salt myminion boto_elb.get_instance_health myelb region=us-east-1 instances="[instance_id,instance_id]" ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: instance_states = conn.describe_instance_health(name, instances) ret = [] for _instance in instance_states: ret.append({'instance_id': _instance.instance_id, 'description': _instance.description, 'state': _instance.state, 'reason_code': _instance.reason_code }) return ret except boto.exception.BotoServerError as error: log.debug(error) return [] def create_policy(name, policy_name, policy_type, policy, region=None, key=None, keyid=None, profile=None): ''' Create an ELB policy. .. versionadded:: 2016.3.0 CLI example: .. code-block:: bash salt myminion boto_elb.create_policy myelb mypolicy LBCookieStickinessPolicyType '{"CookieExpirationPeriod": 3600}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not exists(name, region, key, keyid, profile): return False try: success = conn.create_lb_policy(name, policy_name, policy_type, policy) if success: log.info('Created policy %s on ELB %s', policy_name, name) return True else: log.error('Failed to create policy %s on ELB %s', policy_name, name) return False except boto.exception.BotoServerError as e: log.error('Failed to create policy %s on ELB %s: %s', policy_name, name, e.message, exc_info_on_loglevel=logging.DEBUG) return False def delete_policy(name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Delete an ELB policy. .. versionadded:: 2016.3.0 CLI example: .. code-block:: bash salt myminion boto_elb.delete_policy myelb mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not exists(name, region, key, keyid, profile): return True try: conn.delete_lb_policy(name, policy_name) log.info('Deleted policy %s on ELB %s', policy_name, name) return True except boto.exception.BotoServerError as e: log.error('Failed to delete policy %s on ELB %s: %s', policy_name, name, e.message, exc_info_on_loglevel=logging.DEBUG) return False def set_listener_policy(name, port, policies=None, region=None, key=None, keyid=None, profile=None): ''' Set the policies of an ELB listener. .. versionadded:: 2016.3.0 CLI example: .. code-block:: Bash salt myminion boto_elb.set_listener_policy myelb 443 "[policy1,policy2]" ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not exists(name, region, key, keyid, profile): return True if policies is None: policies = [] try: conn.set_lb_policies_of_listener(name, port, policies) log.info('Set policies %s on ELB %s listener %s', policies, name, port) except boto.exception.BotoServerError as e: log.info('Failed to set policy %s on ELB %s listener %s: %s', policies, name, port, e.message, exc_info_on_loglevel=logging.DEBUG) return False return True def set_backend_policy(name, port, policies=None, region=None, key=None, keyid=None, profile=None): ''' Set the policies of an ELB backend server. CLI example: salt myminion boto_elb.set_backend_policy myelb 443 "[policy1,policy2]" ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not exists(name, region, key, keyid, profile): return True if policies is None: policies = [] try: conn.set_lb_policies_of_backend_server(name, port, policies) log.info('Set policies %s on ELB %s backend server %s', policies, name, port) except boto.exception.BotoServerError as e: log.info('Failed to set policy %s on ELB %s backend server %s: %s', policies, name, port, e.message, exc_info_on_loglevel=logging.DEBUG) return False return True def set_tags(name, tags, region=None, key=None, keyid=None, profile=None): ''' Add the tags on an ELB .. versionadded:: 2016.3.0 name name of the ELB tags dict of name/value pair tags CLI Example: .. code-block:: bash salt myminion boto_elb.set_tags my-elb-name "{'Tag1': 'Value', 'Tag2': 'Another Value'}" ''' if exists(name, region, key, keyid, profile): conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) ret = _add_tags(conn, name, tags) return ret else: return False def delete_tags(name, tags, region=None, key=None, keyid=None, profile=None): ''' Add the tags on an ELB name name of the ELB tags list of tags to remove CLI Example: .. code-block:: bash salt myminion boto_elb.delete_tags my-elb-name ['TagToRemove1', 'TagToRemove2'] ''' if exists(name, region, key, keyid, profile): conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) ret = _remove_tags(conn, name, tags) return ret else: return False def _build_tag_param_list(params, tags): ''' helper function to build a tag parameter list to send ''' keys = sorted(tags.keys()) i = 1 for key in keys: value = tags[key] params['Tags.member.{0}.Key'.format(i)] = key if value is not None: params['Tags.member.{0}.Value'.format(i)] = value i += 1 def _add_tags(conn, load_balancer_names, tags): ''' Create new metadata tags for the specified resource ids. :type load_balancer_names: list :param load_balancer_names: A list of load balancer names. :type tags: dict :param tags: A dictionary containing the name/value pairs. If you want to create only a tag name, the value for that tag should be the empty string (e.g. ''). ''' params = {} conn.build_list_params(params, load_balancer_names, 'LoadBalancerNames.member.%d') _build_tag_param_list(params, tags) return conn.get_status('AddTags', params, verb='POST') def _remove_tags(conn, load_balancer_names, tags): ''' Delete metadata tags for the specified resource ids. :type load_balancer_names: list :param load_balancer_names: A list of load balancer names. :type tags: list :param tags: A list containing just tag names for the tags to be deleted. ''' params = {} conn.build_list_params(params, load_balancer_names, 'LoadBalancerNames.member.%d') conn.build_list_params(params, tags, 'Tags.member.%d.Key') return conn.get_status('RemoveTags', params, verb='POST')
saltstack/salt
salt/modules/boto_elb.py
_add_tags
python
def _add_tags(conn, load_balancer_names, tags): ''' Create new metadata tags for the specified resource ids. :type load_balancer_names: list :param load_balancer_names: A list of load balancer names. :type tags: dict :param tags: A dictionary containing the name/value pairs. If you want to create only a tag name, the value for that tag should be the empty string (e.g. ''). ''' params = {} conn.build_list_params(params, load_balancer_names, 'LoadBalancerNames.member.%d') _build_tag_param_list(params, tags) return conn.get_status('AddTags', params, verb='POST')
Create new metadata tags for the specified resource ids. :type load_balancer_names: list :param load_balancer_names: A list of load balancer names. :type tags: dict :param tags: A dictionary containing the name/value pairs. If you want to create only a tag name, the value for that tag should be the empty string (e.g. '').
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_elb.py#L1056-L1073
[ "def _build_tag_param_list(params, tags):\n '''\n helper function to build a tag parameter list to send\n '''\n keys = sorted(tags.keys())\n i = 1\n for key in keys:\n value = tags[key]\n params['Tags.member.{0}.Key'.format(i)] = key\n if value is not None:\n params['Tags.member.{0}.Value'.format(i)] = value\n i += 1\n" ]
# -*- coding: utf-8 -*- ''' Connection module for Amazon ELB .. versionadded:: 2014.7.0 :configuration: This module accepts explicit elb credentials but can also utilize IAM roles assigned to the instance through Instance Profiles. Dynamic credentials are then automatically obtained from AWS API and no further configuration is necessary. More Information available at: .. code-block:: text http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/iam-roles-for-amazon-ec2.html If IAM roles are not used you need to specify them either in a pillar or in the minion's config file: .. code-block:: yaml elb.keyid: GKTADJGHEIQSXMKKRBJ08H elb.key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs A region may also be specified in the configuration: .. code-block:: yaml elb.region: us-east-1 If a region is not specified, the default is us-east-1. It's also possible to specify key, keyid and region via a profile, either as a passed in dict, or as a string to pull from pillars or minion config: .. code-block:: yaml myprofile: keyid: GKTADJGHEIQSXMKKRBJ08H key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs region: us-east-1 :depends: boto >= 2.33.0 ''' # keep lint from choking on _get_conn and _cache_id # pylint: disable=E0602 from __future__ import absolute_import, print_function, unicode_literals # Import Python libs import logging import time log = logging.getLogger(__name__) # Import Salt libs import salt.utils.json import salt.utils.odict as odict import salt.utils.versions # Import third party libs from salt.ext import six try: import boto import boto.ec2 # pylint: enable=unused-import from boto.ec2.elb import HealthCheck from boto.ec2.elb.attributes import AccessLogAttribute from boto.ec2.elb.attributes import ConnectionDrainingAttribute from boto.ec2.elb.attributes import ConnectionSettingAttribute from boto.ec2.elb.attributes import CrossZoneLoadBalancingAttribute logging.getLogger('boto').setLevel(logging.CRITICAL) HAS_BOTO = True except ImportError: HAS_BOTO = False def __virtual__(): ''' Only load if boto libraries exist. ''' # connection settings were added in 2.33.0 has_boto_reqs = salt.utils.versions.check_boto_reqs( boto_ver='2.33.0', check_boto3=False ) if has_boto_reqs is True: __utils__['boto.assign_funcs'](__name__, 'elb', module='ec2.elb', pack=__salt__) return has_boto_reqs def exists(name, region=None, key=None, keyid=None, profile=None): ''' Check to see if an ELB exists. CLI example: .. code-block:: bash salt myminion boto_elb.exists myelb region=us-east-1 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: elb = conn.get_all_load_balancers(load_balancer_names=[name]) if elb: return True else: log.debug('The load balancer does not exist in region %s', region) return False except boto.exception.BotoServerError as error: log.warning(error) return False def get_all_elbs(region=None, key=None, keyid=None, profile=None): ''' Return all load balancers associated with an account CLI example: .. code-block:: bash salt myminion boto_elb.get_all_elbs region=us-east-1 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: return [e for e in conn.get_all_load_balancers()] except boto.exception.BotoServerError as error: log.warning(error) return [] def list_elbs(region=None, key=None, keyid=None, profile=None): ''' Return names of all load balancers associated with an account CLI example: .. code-block:: bash salt myminion boto_elb.list_elbs region=us-east-1 ''' return [e.name for e in get_all_elbs(region=region, key=key, keyid=keyid, profile=profile)] def get_elb_config(name, region=None, key=None, keyid=None, profile=None): ''' Get an ELB configuration. CLI example: .. code-block:: bash salt myminion boto_elb.exists myelb region=us-east-1 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) retries = 30 while retries: try: lb = conn.get_all_load_balancers(load_balancer_names=[name]) lb = lb[0] ret = {} ret['availability_zones'] = lb.availability_zones listeners = [] for _listener in lb.listeners: listener_dict = {} listener_dict['elb_port'] = _listener.load_balancer_port listener_dict['elb_protocol'] = _listener.protocol listener_dict['instance_port'] = _listener.instance_port listener_dict['instance_protocol'] = _listener.instance_protocol listener_dict['policies'] = _listener.policy_names if _listener.ssl_certificate_id: listener_dict['certificate'] = _listener.ssl_certificate_id listeners.append(listener_dict) ret['listeners'] = listeners backends = [] for _backend in lb.backends: bs_dict = {} bs_dict['instance_port'] = _backend.instance_port bs_dict['policies'] = [p.policy_name for p in _backend.policies] backends.append(bs_dict) ret['backends'] = backends ret['subnets'] = lb.subnets ret['security_groups'] = lb.security_groups ret['scheme'] = lb.scheme ret['dns_name'] = lb.dns_name ret['tags'] = _get_all_tags(conn, name) lb_policy_lists = [ lb.policies.app_cookie_stickiness_policies, lb.policies.lb_cookie_stickiness_policies, lb.policies.other_policies ] policies = [] for policy_list in lb_policy_lists: policies += [p.policy_name for p in policy_list] ret['policies'] = policies return ret except boto.exception.BotoServerError as error: if error.error_code == 'Throttling': log.debug('Throttled by AWS API, will retry in 5 seconds.') time.sleep(5) retries -= 1 continue log.error('Error fetching config for ELB %s: %s', name, error.message) log.error(error) return {} return {} def listener_dict_to_tuple(listener): ''' Convert an ELB listener dict into a listener tuple used by certain parts of the AWS ELB API. CLI example: .. code-block:: bash salt myminion boto_elb.listener_dict_to_tuple '{"elb_port":80,"instance_port":80,"elb_protocol":"HTTP"}' ''' # We define all listeners as complex listeners. if 'instance_protocol' not in listener: instance_protocol = listener['elb_protocol'].upper() else: instance_protocol = listener['instance_protocol'].upper() listener_tuple = [listener['elb_port'], listener['instance_port'], listener['elb_protocol'], instance_protocol] if 'certificate' in listener: listener_tuple.append(listener['certificate']) return tuple(listener_tuple) def create(name, availability_zones, listeners, subnets=None, security_groups=None, scheme='internet-facing', region=None, key=None, keyid=None, profile=None): ''' Create an ELB CLI example to create an ELB: .. code-block:: bash salt myminion boto_elb.create myelb '["us-east-1a", "us-east-1e"]' '{"elb_port": 443, "elb_protocol": "HTTPS", ...}' region=us-east-1 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if exists(name, region, key, keyid, profile): return True if isinstance(availability_zones, six.string_types): availability_zones = salt.utils.json.loads(availability_zones) if isinstance(listeners, six.string_types): listeners = salt.utils.json.loads(listeners) _complex_listeners = [] for listener in listeners: _complex_listeners.append(listener_dict_to_tuple(listener)) try: lb = conn.create_load_balancer(name=name, zones=availability_zones, subnets=subnets, security_groups=security_groups, scheme=scheme, complex_listeners=_complex_listeners) if lb: log.info('Created ELB %s', name) return True else: log.error('Failed to create ELB %s', name) return False except boto.exception.BotoServerError as error: log.error('Failed to create ELB %s: %s: %s', name, error.error_code, error.message, exc_info_on_loglevel=logging.DEBUG) return False def delete(name, region=None, key=None, keyid=None, profile=None): ''' Delete an ELB. CLI example to delete an ELB: .. code-block:: bash salt myminion boto_elb.delete myelb region=us-east-1 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not exists(name, region, key, keyid, profile): return True try: conn.delete_load_balancer(name) log.info('Deleted ELB %s.', name) return True except boto.exception.BotoServerError as error: log.error('Failed to delete ELB %s', name, exc_info_on_loglevel=logging.DEBUG) return False def create_listeners(name, listeners, region=None, key=None, keyid=None, profile=None): ''' Create listeners on an ELB. CLI example: .. code-block:: bash salt myminion boto_elb.create_listeners myelb '[["HTTPS", "HTTP", 443, 80, "arn:aws:iam::11 11111:server-certificate/mycert"]]' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if isinstance(listeners, six.string_types): listeners = salt.utils.json.loads(listeners) _complex_listeners = [] for listener in listeners: _complex_listeners.append(listener_dict_to_tuple(listener)) try: conn.create_load_balancer_listeners(name, [], _complex_listeners) log.info('Created ELB listeners on %s', name) return True except boto.exception.BotoServerError as error: log.error('Failed to create ELB listeners on %s: %s', name, error, exc_info_on_loglevel=logging.DEBUG) return False def delete_listeners(name, ports, region=None, key=None, keyid=None, profile=None): ''' Delete listeners on an ELB. CLI example: .. code-block:: bash salt myminion boto_elb.delete_listeners myelb '[80,443]' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if isinstance(ports, six.string_types): ports = salt.utils.json.loads(ports) try: conn.delete_load_balancer_listeners(name, ports) log.info('Deleted ELB listeners on %s', name) return True except boto.exception.BotoServerError as error: log.error('Failed to delete ELB listeners on %s: %s', name, error, exc_info_on_loglevel=logging.DEBUG) return False def apply_security_groups(name, security_groups, region=None, key=None, keyid=None, profile=None): ''' Apply security groups to ELB. CLI example: .. code-block:: bash salt myminion boto_elb.apply_security_groups myelb '["mysecgroup1"]' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if isinstance(security_groups, six.string_types): security_groups = salt.utils.json.loads(security_groups) try: conn.apply_security_groups_to_lb(name, security_groups) log.info('Applied security_groups on ELB %s', name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to appply security_groups on ELB %s: %s', name, e.message) return False def enable_availability_zones(name, availability_zones, region=None, key=None, keyid=None, profile=None): ''' Enable availability zones for ELB. CLI example: .. code-block:: bash salt myminion boto_elb.enable_availability_zones myelb '["us-east-1a"]' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if isinstance(availability_zones, six.string_types): availability_zones = salt.utils.json.loads(availability_zones) try: conn.enable_availability_zones(name, availability_zones) log.info('Enabled availability_zones on ELB %s', name) return True except boto.exception.BotoServerError as error: log.error('Failed to enable availability_zones on ELB %s: %s', name, error) return False def disable_availability_zones(name, availability_zones, region=None, key=None, keyid=None, profile=None): ''' Disable availability zones for ELB. CLI example: .. code-block:: bash salt myminion boto_elb.disable_availability_zones myelb '["us-east-1a"]' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if isinstance(availability_zones, six.string_types): availability_zones = salt.utils.json.loads(availability_zones) try: conn.disable_availability_zones(name, availability_zones) log.info('Disabled availability_zones on ELB %s', name) return True except boto.exception.BotoServerError as error: log.error('Failed to disable availability_zones on ELB %s: %s', name, error, exc_info_on_loglevel=logging.DEBUG) return False def attach_subnets(name, subnets, region=None, key=None, keyid=None, profile=None): ''' Attach ELB to subnets. CLI example: .. code-block:: bash salt myminion boto_elb.attach_subnets myelb '["mysubnet"]' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if isinstance(subnets, six.string_types): subnets = salt.utils.json.loads(subnets) try: conn.attach_lb_to_subnets(name, subnets) log.info('Attached ELB %s on subnets.', name) return True except boto.exception.BotoServerError as error: log.error('Failed to attach ELB %s on subnets: %s', name, error, exc_info_on_loglevel=logging.DEBUG) return False def detach_subnets(name, subnets, region=None, key=None, keyid=None, profile=None): ''' Detach ELB from subnets. CLI example: .. code-block:: bash salt myminion boto_elb.detach_subnets myelb '["mysubnet"]' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if isinstance(subnets, six.string_types): subnets = salt.utils.json.loads(subnets) try: conn.detach_lb_from_subnets(name, subnets) log.info('Detached ELB %s from subnets.', name) return True except boto.exception.BotoServerError as error: log.error('Failed to detach ELB %s from subnets: %s', name, error, exc_info_on_loglevel=logging.DEBUG) return False def get_attributes(name, region=None, key=None, keyid=None, profile=None): ''' Check to see if attributes are set on an ELB. CLI example: .. code-block:: bash salt myminion boto_elb.get_attributes myelb ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) retries = 30 while retries: try: lbattrs = conn.get_all_lb_attributes(name) ret = odict.OrderedDict() ret['access_log'] = odict.OrderedDict() ret['cross_zone_load_balancing'] = odict.OrderedDict() ret['connection_draining'] = odict.OrderedDict() ret['connecting_settings'] = odict.OrderedDict() al = lbattrs.access_log czlb = lbattrs.cross_zone_load_balancing cd = lbattrs.connection_draining cs = lbattrs.connecting_settings ret['access_log']['enabled'] = al.enabled ret['access_log']['s3_bucket_name'] = al.s3_bucket_name ret['access_log']['s3_bucket_prefix'] = al.s3_bucket_prefix ret['access_log']['emit_interval'] = al.emit_interval ret['cross_zone_load_balancing']['enabled'] = czlb.enabled ret['connection_draining']['enabled'] = cd.enabled ret['connection_draining']['timeout'] = cd.timeout ret['connecting_settings']['idle_timeout'] = cs.idle_timeout return ret except boto.exception.BotoServerError as e: if e.error_code == 'Throttling': log.debug("Throttled by AWS API, will retry in 5 seconds...") time.sleep(5) retries -= 1 continue log.error('ELB %s does not exist: %s', name, e.message) return {} return {} def set_attributes(name, attributes, region=None, key=None, keyid=None, profile=None): ''' Set attributes on an ELB. name (string) Name of the ELB instance to set attributes for attributes A dict of attributes to set. Valid attributes are: access_log (dict) enabled (bool) Enable storage of access logs. s3_bucket_name (string) The name of the S3 bucket to place logs. s3_bucket_prefix (string) Prefix for the log file name. emit_interval (int) Interval for storing logs in S3 in minutes. Valid values are 5 and 60. connection_draining (dict) enabled (bool) Enable connection draining. timeout (int) Maximum allowed time in seconds for sending existing connections to an instance that is deregistering or unhealthy. Default is 300. cross_zone_load_balancing (dict) enabled (bool) Enable cross-zone load balancing. CLI example to set attributes on an ELB: .. code-block:: bash salt myminion boto_elb.set_attributes myelb '{"access_log": {"enabled": "true", "s3_bucket_name": "mybucket", "s3_bucket_prefix": "mylogs/", "emit_interval": "5"}}' region=us-east-1 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) al = attributes.get('access_log', {}) czlb = attributes.get('cross_zone_load_balancing', {}) cd = attributes.get('connection_draining', {}) cs = attributes.get('connecting_settings', {}) if not al and not czlb and not cd and not cs: log.error('No supported attributes for ELB.') return False if al: _al = AccessLogAttribute() _al.enabled = al.get('enabled', False) if not _al.enabled: msg = 'Access log attribute configured, but enabled config missing' log.error(msg) return False _al.s3_bucket_name = al.get('s3_bucket_name', None) _al.s3_bucket_prefix = al.get('s3_bucket_prefix', None) _al.emit_interval = al.get('emit_interval', None) added_attr = conn.modify_lb_attribute(name, 'accessLog', _al) if added_attr: log.info('Added access_log attribute to %s elb.', name) else: log.error('Failed to add access_log attribute to %s elb.', name) return False if czlb: _czlb = CrossZoneLoadBalancingAttribute() _czlb.enabled = czlb['enabled'] added_attr = conn.modify_lb_attribute(name, 'crossZoneLoadBalancing', _czlb.enabled) if added_attr: log.info('Added cross_zone_load_balancing attribute to %s elb.', name) else: log.error('Failed to add cross_zone_load_balancing attribute.') return False if cd: _cd = ConnectionDrainingAttribute() _cd.enabled = cd['enabled'] _cd.timeout = cd.get('timeout', 300) added_attr = conn.modify_lb_attribute(name, 'connectionDraining', _cd) if added_attr: log.info('Added connection_draining attribute to %s elb.', name) else: log.error('Failed to add connection_draining attribute.') return False if cs: _cs = ConnectionSettingAttribute() _cs.idle_timeout = cs.get('idle_timeout', 60) added_attr = conn.modify_lb_attribute(name, 'connectingSettings', _cs) if added_attr: log.info('Added connecting_settings attribute to %s elb.', name) else: log.error('Failed to add connecting_settings attribute.') return False return True def get_health_check(name, region=None, key=None, keyid=None, profile=None): ''' Get the health check configured for this ELB. CLI example: .. code-block:: bash salt myminion boto_elb.get_health_check myelb ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) retries = 30 while True: try: lb = conn.get_all_load_balancers(load_balancer_names=[name]) lb = lb[0] ret = odict.OrderedDict() hc = lb.health_check ret['interval'] = hc.interval ret['target'] = hc.target ret['healthy_threshold'] = hc.healthy_threshold ret['timeout'] = hc.timeout ret['unhealthy_threshold'] = hc.unhealthy_threshold return ret except boto.exception.BotoServerError as e: if retries and e.code == 'Throttling': log.debug('Throttled by AWS API, will retry in 5 seconds.') time.sleep(5) retries -= 1 continue log.error('ELB %s not found.', name, exc_info_on_logleve=logging.DEBUG) return {} def set_health_check(name, health_check, region=None, key=None, keyid=None, profile=None): ''' Set attributes on an ELB. CLI example to set attributes on an ELB: .. code-block:: bash salt myminion boto_elb.set_health_check myelb '{"target": "HTTP:80/"}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) retries = 30 hc = HealthCheck(**health_check) while True: try: conn.configure_health_check(name, hc) log.info('Configured health check on ELB %s', name) return True except boto.exception.BotoServerError as error: if retries and e.code == 'Throttling': log.debug('Throttled by AWS API, will retry in 5 seconds.') time.sleep(5) retries -= 1 continue log.exception('Failed to configure health check on ELB %s', name) return False def register_instances(name, instances, region=None, key=None, keyid=None, profile=None): ''' Register instances with an ELB. Instances is either a string instance id or a list of string instance id's. Returns: - ``True``: instance(s) registered successfully - ``False``: instance(s) failed to be registered CLI example: .. code-block:: bash salt myminion boto_elb.register_instances myelb instance_id salt myminion boto_elb.register_instances myelb "[instance_id,instance_id]" ''' # convert instances to list type, enabling consistent use of instances # variable throughout the register_instances method if isinstance(instances, six.string_types) or isinstance(instances, six.text_type): instances = [instances] conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: registered_instances = conn.register_instances(name, instances) except boto.exception.BotoServerError as error: log.warning(error) return False registered_instance_ids = [instance.id for instance in registered_instances] # register_failues is a set that will contain any instances that were not # able to be registered with the given ELB register_failures = set(instances).difference(set(registered_instance_ids)) if register_failures: log.warning('Instance(s): %s not registered with ELB %s.', list(register_failures), name) register_result = False else: register_result = True return register_result def deregister_instances(name, instances, region=None, key=None, keyid=None, profile=None): ''' Deregister instances with an ELB. Instances is either a string instance id or a list of string instance id's. Returns: - ``True``: instance(s) deregistered successfully - ``False``: instance(s) failed to be deregistered - ``None``: instance(s) not valid or not registered, no action taken CLI example: .. code-block:: bash salt myminion boto_elb.deregister_instances myelb instance_id salt myminion boto_elb.deregister_instances myelb "[instance_id, instance_id]" ''' # convert instances to list type, enabling consistent use of instances # variable throughout the deregister_instances method if isinstance(instances, six.string_types) or isinstance(instances, six.text_type): instances = [instances] conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: registered_instances = conn.deregister_instances(name, instances) except boto.exception.BotoServerError as error: # if the instance(s) given as an argument are not members of the ELB # boto returns error.error_code == 'InvalidInstance' # deregister_instances returns "None" because the instances are # effectively deregistered from ELB if error.error_code == 'InvalidInstance': log.warning( 'One or more of instance(s) %s are not part of ELB %s. ' 'deregister_instances not performed.', instances, name ) return None else: log.warning(error) return False registered_instance_ids = [instance.id for instance in registered_instances] # deregister_failures is a set that will contain any instances that were # unable to be deregistered from the given ELB deregister_failures = set(instances).intersection(set(registered_instance_ids)) if deregister_failures: log.warning( 'Instance(s): %s not deregistered from ELB %s.', list(deregister_failures), name ) deregister_result = False else: deregister_result = True return deregister_result def set_instances(name, instances, test=False, region=None, key=None, keyid=None, profile=None): ''' Set the instances assigned to an ELB to exactly the list given CLI example: .. code-block:: bash salt myminion boto_elb.set_instances myelb region=us-east-1 instances="[instance_id,instance_id]" ''' ret = True current = set([i['instance_id'] for i in get_instance_health(name, region, key, keyid, profile)]) desired = set(instances) add = desired - current remove = current - desired if test: return bool(add or remove) if remove: if deregister_instances(name, list(remove), region, key, keyid, profile) is False: ret = False if add: if register_instances(name, list(add), region, key, keyid, profile) is False: ret = False return ret def get_instance_health(name, region=None, key=None, keyid=None, profile=None, instances=None): ''' Get a list of instances and their health state CLI example: .. code-block:: bash salt myminion boto_elb.get_instance_health myelb salt myminion boto_elb.get_instance_health myelb region=us-east-1 instances="[instance_id,instance_id]" ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: instance_states = conn.describe_instance_health(name, instances) ret = [] for _instance in instance_states: ret.append({'instance_id': _instance.instance_id, 'description': _instance.description, 'state': _instance.state, 'reason_code': _instance.reason_code }) return ret except boto.exception.BotoServerError as error: log.debug(error) return [] def create_policy(name, policy_name, policy_type, policy, region=None, key=None, keyid=None, profile=None): ''' Create an ELB policy. .. versionadded:: 2016.3.0 CLI example: .. code-block:: bash salt myminion boto_elb.create_policy myelb mypolicy LBCookieStickinessPolicyType '{"CookieExpirationPeriod": 3600}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not exists(name, region, key, keyid, profile): return False try: success = conn.create_lb_policy(name, policy_name, policy_type, policy) if success: log.info('Created policy %s on ELB %s', policy_name, name) return True else: log.error('Failed to create policy %s on ELB %s', policy_name, name) return False except boto.exception.BotoServerError as e: log.error('Failed to create policy %s on ELB %s: %s', policy_name, name, e.message, exc_info_on_loglevel=logging.DEBUG) return False def delete_policy(name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Delete an ELB policy. .. versionadded:: 2016.3.0 CLI example: .. code-block:: bash salt myminion boto_elb.delete_policy myelb mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not exists(name, region, key, keyid, profile): return True try: conn.delete_lb_policy(name, policy_name) log.info('Deleted policy %s on ELB %s', policy_name, name) return True except boto.exception.BotoServerError as e: log.error('Failed to delete policy %s on ELB %s: %s', policy_name, name, e.message, exc_info_on_loglevel=logging.DEBUG) return False def set_listener_policy(name, port, policies=None, region=None, key=None, keyid=None, profile=None): ''' Set the policies of an ELB listener. .. versionadded:: 2016.3.0 CLI example: .. code-block:: Bash salt myminion boto_elb.set_listener_policy myelb 443 "[policy1,policy2]" ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not exists(name, region, key, keyid, profile): return True if policies is None: policies = [] try: conn.set_lb_policies_of_listener(name, port, policies) log.info('Set policies %s on ELB %s listener %s', policies, name, port) except boto.exception.BotoServerError as e: log.info('Failed to set policy %s on ELB %s listener %s: %s', policies, name, port, e.message, exc_info_on_loglevel=logging.DEBUG) return False return True def set_backend_policy(name, port, policies=None, region=None, key=None, keyid=None, profile=None): ''' Set the policies of an ELB backend server. CLI example: salt myminion boto_elb.set_backend_policy myelb 443 "[policy1,policy2]" ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not exists(name, region, key, keyid, profile): return True if policies is None: policies = [] try: conn.set_lb_policies_of_backend_server(name, port, policies) log.info('Set policies %s on ELB %s backend server %s', policies, name, port) except boto.exception.BotoServerError as e: log.info('Failed to set policy %s on ELB %s backend server %s: %s', policies, name, port, e.message, exc_info_on_loglevel=logging.DEBUG) return False return True def set_tags(name, tags, region=None, key=None, keyid=None, profile=None): ''' Add the tags on an ELB .. versionadded:: 2016.3.0 name name of the ELB tags dict of name/value pair tags CLI Example: .. code-block:: bash salt myminion boto_elb.set_tags my-elb-name "{'Tag1': 'Value', 'Tag2': 'Another Value'}" ''' if exists(name, region, key, keyid, profile): conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) ret = _add_tags(conn, name, tags) return ret else: return False def delete_tags(name, tags, region=None, key=None, keyid=None, profile=None): ''' Add the tags on an ELB name name of the ELB tags list of tags to remove CLI Example: .. code-block:: bash salt myminion boto_elb.delete_tags my-elb-name ['TagToRemove1', 'TagToRemove2'] ''' if exists(name, region, key, keyid, profile): conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) ret = _remove_tags(conn, name, tags) return ret else: return False def _build_tag_param_list(params, tags): ''' helper function to build a tag parameter list to send ''' keys = sorted(tags.keys()) i = 1 for key in keys: value = tags[key] params['Tags.member.{0}.Key'.format(i)] = key if value is not None: params['Tags.member.{0}.Value'.format(i)] = value i += 1 def _get_all_tags(conn, load_balancer_names=None): ''' Retrieve all the metadata tags associated with your ELB(s). :type load_balancer_names: list :param load_balancer_names: An optional list of load balancer names. :rtype: list :return: A list of :class:`boto.ec2.elb.tag.Tag` objects ''' params = {} if load_balancer_names: conn.build_list_params(params, load_balancer_names, 'LoadBalancerNames.member.%d') tags = conn.get_object( 'DescribeTags', params, __utils__['boto_elb_tag.get_tag_descriptions'](), verb='POST' ) if tags[load_balancer_names]: return tags[load_balancer_names] else: return None def _remove_tags(conn, load_balancer_names, tags): ''' Delete metadata tags for the specified resource ids. :type load_balancer_names: list :param load_balancer_names: A list of load balancer names. :type tags: list :param tags: A list containing just tag names for the tags to be deleted. ''' params = {} conn.build_list_params(params, load_balancer_names, 'LoadBalancerNames.member.%d') conn.build_list_params(params, tags, 'Tags.member.%d.Key') return conn.get_status('RemoveTags', params, verb='POST')
saltstack/salt
salt/modules/boto_elb.py
_remove_tags
python
def _remove_tags(conn, load_balancer_names, tags): ''' Delete metadata tags for the specified resource ids. :type load_balancer_names: list :param load_balancer_names: A list of load balancer names. :type tags: list :param tags: A list containing just tag names for the tags to be deleted. ''' params = {} conn.build_list_params(params, load_balancer_names, 'LoadBalancerNames.member.%d') conn.build_list_params(params, tags, 'Tags.member.%d.Key') return conn.get_status('RemoveTags', params, verb='POST')
Delete metadata tags for the specified resource ids. :type load_balancer_names: list :param load_balancer_names: A list of load balancer names. :type tags: list :param tags: A list containing just tag names for the tags to be deleted.
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_elb.py#L1076-L1092
null
# -*- coding: utf-8 -*- ''' Connection module for Amazon ELB .. versionadded:: 2014.7.0 :configuration: This module accepts explicit elb credentials but can also utilize IAM roles assigned to the instance through Instance Profiles. Dynamic credentials are then automatically obtained from AWS API and no further configuration is necessary. More Information available at: .. code-block:: text http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/iam-roles-for-amazon-ec2.html If IAM roles are not used you need to specify them either in a pillar or in the minion's config file: .. code-block:: yaml elb.keyid: GKTADJGHEIQSXMKKRBJ08H elb.key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs A region may also be specified in the configuration: .. code-block:: yaml elb.region: us-east-1 If a region is not specified, the default is us-east-1. It's also possible to specify key, keyid and region via a profile, either as a passed in dict, or as a string to pull from pillars or minion config: .. code-block:: yaml myprofile: keyid: GKTADJGHEIQSXMKKRBJ08H key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs region: us-east-1 :depends: boto >= 2.33.0 ''' # keep lint from choking on _get_conn and _cache_id # pylint: disable=E0602 from __future__ import absolute_import, print_function, unicode_literals # Import Python libs import logging import time log = logging.getLogger(__name__) # Import Salt libs import salt.utils.json import salt.utils.odict as odict import salt.utils.versions # Import third party libs from salt.ext import six try: import boto import boto.ec2 # pylint: enable=unused-import from boto.ec2.elb import HealthCheck from boto.ec2.elb.attributes import AccessLogAttribute from boto.ec2.elb.attributes import ConnectionDrainingAttribute from boto.ec2.elb.attributes import ConnectionSettingAttribute from boto.ec2.elb.attributes import CrossZoneLoadBalancingAttribute logging.getLogger('boto').setLevel(logging.CRITICAL) HAS_BOTO = True except ImportError: HAS_BOTO = False def __virtual__(): ''' Only load if boto libraries exist. ''' # connection settings were added in 2.33.0 has_boto_reqs = salt.utils.versions.check_boto_reqs( boto_ver='2.33.0', check_boto3=False ) if has_boto_reqs is True: __utils__['boto.assign_funcs'](__name__, 'elb', module='ec2.elb', pack=__salt__) return has_boto_reqs def exists(name, region=None, key=None, keyid=None, profile=None): ''' Check to see if an ELB exists. CLI example: .. code-block:: bash salt myminion boto_elb.exists myelb region=us-east-1 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: elb = conn.get_all_load_balancers(load_balancer_names=[name]) if elb: return True else: log.debug('The load balancer does not exist in region %s', region) return False except boto.exception.BotoServerError as error: log.warning(error) return False def get_all_elbs(region=None, key=None, keyid=None, profile=None): ''' Return all load balancers associated with an account CLI example: .. code-block:: bash salt myminion boto_elb.get_all_elbs region=us-east-1 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: return [e for e in conn.get_all_load_balancers()] except boto.exception.BotoServerError as error: log.warning(error) return [] def list_elbs(region=None, key=None, keyid=None, profile=None): ''' Return names of all load balancers associated with an account CLI example: .. code-block:: bash salt myminion boto_elb.list_elbs region=us-east-1 ''' return [e.name for e in get_all_elbs(region=region, key=key, keyid=keyid, profile=profile)] def get_elb_config(name, region=None, key=None, keyid=None, profile=None): ''' Get an ELB configuration. CLI example: .. code-block:: bash salt myminion boto_elb.exists myelb region=us-east-1 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) retries = 30 while retries: try: lb = conn.get_all_load_balancers(load_balancer_names=[name]) lb = lb[0] ret = {} ret['availability_zones'] = lb.availability_zones listeners = [] for _listener in lb.listeners: listener_dict = {} listener_dict['elb_port'] = _listener.load_balancer_port listener_dict['elb_protocol'] = _listener.protocol listener_dict['instance_port'] = _listener.instance_port listener_dict['instance_protocol'] = _listener.instance_protocol listener_dict['policies'] = _listener.policy_names if _listener.ssl_certificate_id: listener_dict['certificate'] = _listener.ssl_certificate_id listeners.append(listener_dict) ret['listeners'] = listeners backends = [] for _backend in lb.backends: bs_dict = {} bs_dict['instance_port'] = _backend.instance_port bs_dict['policies'] = [p.policy_name for p in _backend.policies] backends.append(bs_dict) ret['backends'] = backends ret['subnets'] = lb.subnets ret['security_groups'] = lb.security_groups ret['scheme'] = lb.scheme ret['dns_name'] = lb.dns_name ret['tags'] = _get_all_tags(conn, name) lb_policy_lists = [ lb.policies.app_cookie_stickiness_policies, lb.policies.lb_cookie_stickiness_policies, lb.policies.other_policies ] policies = [] for policy_list in lb_policy_lists: policies += [p.policy_name for p in policy_list] ret['policies'] = policies return ret except boto.exception.BotoServerError as error: if error.error_code == 'Throttling': log.debug('Throttled by AWS API, will retry in 5 seconds.') time.sleep(5) retries -= 1 continue log.error('Error fetching config for ELB %s: %s', name, error.message) log.error(error) return {} return {} def listener_dict_to_tuple(listener): ''' Convert an ELB listener dict into a listener tuple used by certain parts of the AWS ELB API. CLI example: .. code-block:: bash salt myminion boto_elb.listener_dict_to_tuple '{"elb_port":80,"instance_port":80,"elb_protocol":"HTTP"}' ''' # We define all listeners as complex listeners. if 'instance_protocol' not in listener: instance_protocol = listener['elb_protocol'].upper() else: instance_protocol = listener['instance_protocol'].upper() listener_tuple = [listener['elb_port'], listener['instance_port'], listener['elb_protocol'], instance_protocol] if 'certificate' in listener: listener_tuple.append(listener['certificate']) return tuple(listener_tuple) def create(name, availability_zones, listeners, subnets=None, security_groups=None, scheme='internet-facing', region=None, key=None, keyid=None, profile=None): ''' Create an ELB CLI example to create an ELB: .. code-block:: bash salt myminion boto_elb.create myelb '["us-east-1a", "us-east-1e"]' '{"elb_port": 443, "elb_protocol": "HTTPS", ...}' region=us-east-1 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if exists(name, region, key, keyid, profile): return True if isinstance(availability_zones, six.string_types): availability_zones = salt.utils.json.loads(availability_zones) if isinstance(listeners, six.string_types): listeners = salt.utils.json.loads(listeners) _complex_listeners = [] for listener in listeners: _complex_listeners.append(listener_dict_to_tuple(listener)) try: lb = conn.create_load_balancer(name=name, zones=availability_zones, subnets=subnets, security_groups=security_groups, scheme=scheme, complex_listeners=_complex_listeners) if lb: log.info('Created ELB %s', name) return True else: log.error('Failed to create ELB %s', name) return False except boto.exception.BotoServerError as error: log.error('Failed to create ELB %s: %s: %s', name, error.error_code, error.message, exc_info_on_loglevel=logging.DEBUG) return False def delete(name, region=None, key=None, keyid=None, profile=None): ''' Delete an ELB. CLI example to delete an ELB: .. code-block:: bash salt myminion boto_elb.delete myelb region=us-east-1 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not exists(name, region, key, keyid, profile): return True try: conn.delete_load_balancer(name) log.info('Deleted ELB %s.', name) return True except boto.exception.BotoServerError as error: log.error('Failed to delete ELB %s', name, exc_info_on_loglevel=logging.DEBUG) return False def create_listeners(name, listeners, region=None, key=None, keyid=None, profile=None): ''' Create listeners on an ELB. CLI example: .. code-block:: bash salt myminion boto_elb.create_listeners myelb '[["HTTPS", "HTTP", 443, 80, "arn:aws:iam::11 11111:server-certificate/mycert"]]' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if isinstance(listeners, six.string_types): listeners = salt.utils.json.loads(listeners) _complex_listeners = [] for listener in listeners: _complex_listeners.append(listener_dict_to_tuple(listener)) try: conn.create_load_balancer_listeners(name, [], _complex_listeners) log.info('Created ELB listeners on %s', name) return True except boto.exception.BotoServerError as error: log.error('Failed to create ELB listeners on %s: %s', name, error, exc_info_on_loglevel=logging.DEBUG) return False def delete_listeners(name, ports, region=None, key=None, keyid=None, profile=None): ''' Delete listeners on an ELB. CLI example: .. code-block:: bash salt myminion boto_elb.delete_listeners myelb '[80,443]' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if isinstance(ports, six.string_types): ports = salt.utils.json.loads(ports) try: conn.delete_load_balancer_listeners(name, ports) log.info('Deleted ELB listeners on %s', name) return True except boto.exception.BotoServerError as error: log.error('Failed to delete ELB listeners on %s: %s', name, error, exc_info_on_loglevel=logging.DEBUG) return False def apply_security_groups(name, security_groups, region=None, key=None, keyid=None, profile=None): ''' Apply security groups to ELB. CLI example: .. code-block:: bash salt myminion boto_elb.apply_security_groups myelb '["mysecgroup1"]' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if isinstance(security_groups, six.string_types): security_groups = salt.utils.json.loads(security_groups) try: conn.apply_security_groups_to_lb(name, security_groups) log.info('Applied security_groups on ELB %s', name) return True except boto.exception.BotoServerError as e: log.debug(e) log.error('Failed to appply security_groups on ELB %s: %s', name, e.message) return False def enable_availability_zones(name, availability_zones, region=None, key=None, keyid=None, profile=None): ''' Enable availability zones for ELB. CLI example: .. code-block:: bash salt myminion boto_elb.enable_availability_zones myelb '["us-east-1a"]' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if isinstance(availability_zones, six.string_types): availability_zones = salt.utils.json.loads(availability_zones) try: conn.enable_availability_zones(name, availability_zones) log.info('Enabled availability_zones on ELB %s', name) return True except boto.exception.BotoServerError as error: log.error('Failed to enable availability_zones on ELB %s: %s', name, error) return False def disable_availability_zones(name, availability_zones, region=None, key=None, keyid=None, profile=None): ''' Disable availability zones for ELB. CLI example: .. code-block:: bash salt myminion boto_elb.disable_availability_zones myelb '["us-east-1a"]' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if isinstance(availability_zones, six.string_types): availability_zones = salt.utils.json.loads(availability_zones) try: conn.disable_availability_zones(name, availability_zones) log.info('Disabled availability_zones on ELB %s', name) return True except boto.exception.BotoServerError as error: log.error('Failed to disable availability_zones on ELB %s: %s', name, error, exc_info_on_loglevel=logging.DEBUG) return False def attach_subnets(name, subnets, region=None, key=None, keyid=None, profile=None): ''' Attach ELB to subnets. CLI example: .. code-block:: bash salt myminion boto_elb.attach_subnets myelb '["mysubnet"]' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if isinstance(subnets, six.string_types): subnets = salt.utils.json.loads(subnets) try: conn.attach_lb_to_subnets(name, subnets) log.info('Attached ELB %s on subnets.', name) return True except boto.exception.BotoServerError as error: log.error('Failed to attach ELB %s on subnets: %s', name, error, exc_info_on_loglevel=logging.DEBUG) return False def detach_subnets(name, subnets, region=None, key=None, keyid=None, profile=None): ''' Detach ELB from subnets. CLI example: .. code-block:: bash salt myminion boto_elb.detach_subnets myelb '["mysubnet"]' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if isinstance(subnets, six.string_types): subnets = salt.utils.json.loads(subnets) try: conn.detach_lb_from_subnets(name, subnets) log.info('Detached ELB %s from subnets.', name) return True except boto.exception.BotoServerError as error: log.error('Failed to detach ELB %s from subnets: %s', name, error, exc_info_on_loglevel=logging.DEBUG) return False def get_attributes(name, region=None, key=None, keyid=None, profile=None): ''' Check to see if attributes are set on an ELB. CLI example: .. code-block:: bash salt myminion boto_elb.get_attributes myelb ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) retries = 30 while retries: try: lbattrs = conn.get_all_lb_attributes(name) ret = odict.OrderedDict() ret['access_log'] = odict.OrderedDict() ret['cross_zone_load_balancing'] = odict.OrderedDict() ret['connection_draining'] = odict.OrderedDict() ret['connecting_settings'] = odict.OrderedDict() al = lbattrs.access_log czlb = lbattrs.cross_zone_load_balancing cd = lbattrs.connection_draining cs = lbattrs.connecting_settings ret['access_log']['enabled'] = al.enabled ret['access_log']['s3_bucket_name'] = al.s3_bucket_name ret['access_log']['s3_bucket_prefix'] = al.s3_bucket_prefix ret['access_log']['emit_interval'] = al.emit_interval ret['cross_zone_load_balancing']['enabled'] = czlb.enabled ret['connection_draining']['enabled'] = cd.enabled ret['connection_draining']['timeout'] = cd.timeout ret['connecting_settings']['idle_timeout'] = cs.idle_timeout return ret except boto.exception.BotoServerError as e: if e.error_code == 'Throttling': log.debug("Throttled by AWS API, will retry in 5 seconds...") time.sleep(5) retries -= 1 continue log.error('ELB %s does not exist: %s', name, e.message) return {} return {} def set_attributes(name, attributes, region=None, key=None, keyid=None, profile=None): ''' Set attributes on an ELB. name (string) Name of the ELB instance to set attributes for attributes A dict of attributes to set. Valid attributes are: access_log (dict) enabled (bool) Enable storage of access logs. s3_bucket_name (string) The name of the S3 bucket to place logs. s3_bucket_prefix (string) Prefix for the log file name. emit_interval (int) Interval for storing logs in S3 in minutes. Valid values are 5 and 60. connection_draining (dict) enabled (bool) Enable connection draining. timeout (int) Maximum allowed time in seconds for sending existing connections to an instance that is deregistering or unhealthy. Default is 300. cross_zone_load_balancing (dict) enabled (bool) Enable cross-zone load balancing. CLI example to set attributes on an ELB: .. code-block:: bash salt myminion boto_elb.set_attributes myelb '{"access_log": {"enabled": "true", "s3_bucket_name": "mybucket", "s3_bucket_prefix": "mylogs/", "emit_interval": "5"}}' region=us-east-1 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) al = attributes.get('access_log', {}) czlb = attributes.get('cross_zone_load_balancing', {}) cd = attributes.get('connection_draining', {}) cs = attributes.get('connecting_settings', {}) if not al and not czlb and not cd and not cs: log.error('No supported attributes for ELB.') return False if al: _al = AccessLogAttribute() _al.enabled = al.get('enabled', False) if not _al.enabled: msg = 'Access log attribute configured, but enabled config missing' log.error(msg) return False _al.s3_bucket_name = al.get('s3_bucket_name', None) _al.s3_bucket_prefix = al.get('s3_bucket_prefix', None) _al.emit_interval = al.get('emit_interval', None) added_attr = conn.modify_lb_attribute(name, 'accessLog', _al) if added_attr: log.info('Added access_log attribute to %s elb.', name) else: log.error('Failed to add access_log attribute to %s elb.', name) return False if czlb: _czlb = CrossZoneLoadBalancingAttribute() _czlb.enabled = czlb['enabled'] added_attr = conn.modify_lb_attribute(name, 'crossZoneLoadBalancing', _czlb.enabled) if added_attr: log.info('Added cross_zone_load_balancing attribute to %s elb.', name) else: log.error('Failed to add cross_zone_load_balancing attribute.') return False if cd: _cd = ConnectionDrainingAttribute() _cd.enabled = cd['enabled'] _cd.timeout = cd.get('timeout', 300) added_attr = conn.modify_lb_attribute(name, 'connectionDraining', _cd) if added_attr: log.info('Added connection_draining attribute to %s elb.', name) else: log.error('Failed to add connection_draining attribute.') return False if cs: _cs = ConnectionSettingAttribute() _cs.idle_timeout = cs.get('idle_timeout', 60) added_attr = conn.modify_lb_attribute(name, 'connectingSettings', _cs) if added_attr: log.info('Added connecting_settings attribute to %s elb.', name) else: log.error('Failed to add connecting_settings attribute.') return False return True def get_health_check(name, region=None, key=None, keyid=None, profile=None): ''' Get the health check configured for this ELB. CLI example: .. code-block:: bash salt myminion boto_elb.get_health_check myelb ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) retries = 30 while True: try: lb = conn.get_all_load_balancers(load_balancer_names=[name]) lb = lb[0] ret = odict.OrderedDict() hc = lb.health_check ret['interval'] = hc.interval ret['target'] = hc.target ret['healthy_threshold'] = hc.healthy_threshold ret['timeout'] = hc.timeout ret['unhealthy_threshold'] = hc.unhealthy_threshold return ret except boto.exception.BotoServerError as e: if retries and e.code == 'Throttling': log.debug('Throttled by AWS API, will retry in 5 seconds.') time.sleep(5) retries -= 1 continue log.error('ELB %s not found.', name, exc_info_on_logleve=logging.DEBUG) return {} def set_health_check(name, health_check, region=None, key=None, keyid=None, profile=None): ''' Set attributes on an ELB. CLI example to set attributes on an ELB: .. code-block:: bash salt myminion boto_elb.set_health_check myelb '{"target": "HTTP:80/"}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) retries = 30 hc = HealthCheck(**health_check) while True: try: conn.configure_health_check(name, hc) log.info('Configured health check on ELB %s', name) return True except boto.exception.BotoServerError as error: if retries and e.code == 'Throttling': log.debug('Throttled by AWS API, will retry in 5 seconds.') time.sleep(5) retries -= 1 continue log.exception('Failed to configure health check on ELB %s', name) return False def register_instances(name, instances, region=None, key=None, keyid=None, profile=None): ''' Register instances with an ELB. Instances is either a string instance id or a list of string instance id's. Returns: - ``True``: instance(s) registered successfully - ``False``: instance(s) failed to be registered CLI example: .. code-block:: bash salt myminion boto_elb.register_instances myelb instance_id salt myminion boto_elb.register_instances myelb "[instance_id,instance_id]" ''' # convert instances to list type, enabling consistent use of instances # variable throughout the register_instances method if isinstance(instances, six.string_types) or isinstance(instances, six.text_type): instances = [instances] conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: registered_instances = conn.register_instances(name, instances) except boto.exception.BotoServerError as error: log.warning(error) return False registered_instance_ids = [instance.id for instance in registered_instances] # register_failues is a set that will contain any instances that were not # able to be registered with the given ELB register_failures = set(instances).difference(set(registered_instance_ids)) if register_failures: log.warning('Instance(s): %s not registered with ELB %s.', list(register_failures), name) register_result = False else: register_result = True return register_result def deregister_instances(name, instances, region=None, key=None, keyid=None, profile=None): ''' Deregister instances with an ELB. Instances is either a string instance id or a list of string instance id's. Returns: - ``True``: instance(s) deregistered successfully - ``False``: instance(s) failed to be deregistered - ``None``: instance(s) not valid or not registered, no action taken CLI example: .. code-block:: bash salt myminion boto_elb.deregister_instances myelb instance_id salt myminion boto_elb.deregister_instances myelb "[instance_id, instance_id]" ''' # convert instances to list type, enabling consistent use of instances # variable throughout the deregister_instances method if isinstance(instances, six.string_types) or isinstance(instances, six.text_type): instances = [instances] conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: registered_instances = conn.deregister_instances(name, instances) except boto.exception.BotoServerError as error: # if the instance(s) given as an argument are not members of the ELB # boto returns error.error_code == 'InvalidInstance' # deregister_instances returns "None" because the instances are # effectively deregistered from ELB if error.error_code == 'InvalidInstance': log.warning( 'One or more of instance(s) %s are not part of ELB %s. ' 'deregister_instances not performed.', instances, name ) return None else: log.warning(error) return False registered_instance_ids = [instance.id for instance in registered_instances] # deregister_failures is a set that will contain any instances that were # unable to be deregistered from the given ELB deregister_failures = set(instances).intersection(set(registered_instance_ids)) if deregister_failures: log.warning( 'Instance(s): %s not deregistered from ELB %s.', list(deregister_failures), name ) deregister_result = False else: deregister_result = True return deregister_result def set_instances(name, instances, test=False, region=None, key=None, keyid=None, profile=None): ''' Set the instances assigned to an ELB to exactly the list given CLI example: .. code-block:: bash salt myminion boto_elb.set_instances myelb region=us-east-1 instances="[instance_id,instance_id]" ''' ret = True current = set([i['instance_id'] for i in get_instance_health(name, region, key, keyid, profile)]) desired = set(instances) add = desired - current remove = current - desired if test: return bool(add or remove) if remove: if deregister_instances(name, list(remove), region, key, keyid, profile) is False: ret = False if add: if register_instances(name, list(add), region, key, keyid, profile) is False: ret = False return ret def get_instance_health(name, region=None, key=None, keyid=None, profile=None, instances=None): ''' Get a list of instances and their health state CLI example: .. code-block:: bash salt myminion boto_elb.get_instance_health myelb salt myminion boto_elb.get_instance_health myelb region=us-east-1 instances="[instance_id,instance_id]" ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: instance_states = conn.describe_instance_health(name, instances) ret = [] for _instance in instance_states: ret.append({'instance_id': _instance.instance_id, 'description': _instance.description, 'state': _instance.state, 'reason_code': _instance.reason_code }) return ret except boto.exception.BotoServerError as error: log.debug(error) return [] def create_policy(name, policy_name, policy_type, policy, region=None, key=None, keyid=None, profile=None): ''' Create an ELB policy. .. versionadded:: 2016.3.0 CLI example: .. code-block:: bash salt myminion boto_elb.create_policy myelb mypolicy LBCookieStickinessPolicyType '{"CookieExpirationPeriod": 3600}' ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not exists(name, region, key, keyid, profile): return False try: success = conn.create_lb_policy(name, policy_name, policy_type, policy) if success: log.info('Created policy %s on ELB %s', policy_name, name) return True else: log.error('Failed to create policy %s on ELB %s', policy_name, name) return False except boto.exception.BotoServerError as e: log.error('Failed to create policy %s on ELB %s: %s', policy_name, name, e.message, exc_info_on_loglevel=logging.DEBUG) return False def delete_policy(name, policy_name, region=None, key=None, keyid=None, profile=None): ''' Delete an ELB policy. .. versionadded:: 2016.3.0 CLI example: .. code-block:: bash salt myminion boto_elb.delete_policy myelb mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not exists(name, region, key, keyid, profile): return True try: conn.delete_lb_policy(name, policy_name) log.info('Deleted policy %s on ELB %s', policy_name, name) return True except boto.exception.BotoServerError as e: log.error('Failed to delete policy %s on ELB %s: %s', policy_name, name, e.message, exc_info_on_loglevel=logging.DEBUG) return False def set_listener_policy(name, port, policies=None, region=None, key=None, keyid=None, profile=None): ''' Set the policies of an ELB listener. .. versionadded:: 2016.3.0 CLI example: .. code-block:: Bash salt myminion boto_elb.set_listener_policy myelb 443 "[policy1,policy2]" ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not exists(name, region, key, keyid, profile): return True if policies is None: policies = [] try: conn.set_lb_policies_of_listener(name, port, policies) log.info('Set policies %s on ELB %s listener %s', policies, name, port) except boto.exception.BotoServerError as e: log.info('Failed to set policy %s on ELB %s listener %s: %s', policies, name, port, e.message, exc_info_on_loglevel=logging.DEBUG) return False return True def set_backend_policy(name, port, policies=None, region=None, key=None, keyid=None, profile=None): ''' Set the policies of an ELB backend server. CLI example: salt myminion boto_elb.set_backend_policy myelb 443 "[policy1,policy2]" ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not exists(name, region, key, keyid, profile): return True if policies is None: policies = [] try: conn.set_lb_policies_of_backend_server(name, port, policies) log.info('Set policies %s on ELB %s backend server %s', policies, name, port) except boto.exception.BotoServerError as e: log.info('Failed to set policy %s on ELB %s backend server %s: %s', policies, name, port, e.message, exc_info_on_loglevel=logging.DEBUG) return False return True def set_tags(name, tags, region=None, key=None, keyid=None, profile=None): ''' Add the tags on an ELB .. versionadded:: 2016.3.0 name name of the ELB tags dict of name/value pair tags CLI Example: .. code-block:: bash salt myminion boto_elb.set_tags my-elb-name "{'Tag1': 'Value', 'Tag2': 'Another Value'}" ''' if exists(name, region, key, keyid, profile): conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) ret = _add_tags(conn, name, tags) return ret else: return False def delete_tags(name, tags, region=None, key=None, keyid=None, profile=None): ''' Add the tags on an ELB name name of the ELB tags list of tags to remove CLI Example: .. code-block:: bash salt myminion boto_elb.delete_tags my-elb-name ['TagToRemove1', 'TagToRemove2'] ''' if exists(name, region, key, keyid, profile): conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) ret = _remove_tags(conn, name, tags) return ret else: return False def _build_tag_param_list(params, tags): ''' helper function to build a tag parameter list to send ''' keys = sorted(tags.keys()) i = 1 for key in keys: value = tags[key] params['Tags.member.{0}.Key'.format(i)] = key if value is not None: params['Tags.member.{0}.Value'.format(i)] = value i += 1 def _get_all_tags(conn, load_balancer_names=None): ''' Retrieve all the metadata tags associated with your ELB(s). :type load_balancer_names: list :param load_balancer_names: An optional list of load balancer names. :rtype: list :return: A list of :class:`boto.ec2.elb.tag.Tag` objects ''' params = {} if load_balancer_names: conn.build_list_params(params, load_balancer_names, 'LoadBalancerNames.member.%d') tags = conn.get_object( 'DescribeTags', params, __utils__['boto_elb_tag.get_tag_descriptions'](), verb='POST' ) if tags[load_balancer_names]: return tags[load_balancer_names] else: return None def _add_tags(conn, load_balancer_names, tags): ''' Create new metadata tags for the specified resource ids. :type load_balancer_names: list :param load_balancer_names: A list of load balancer names. :type tags: dict :param tags: A dictionary containing the name/value pairs. If you want to create only a tag name, the value for that tag should be the empty string (e.g. ''). ''' params = {} conn.build_list_params(params, load_balancer_names, 'LoadBalancerNames.member.%d') _build_tag_param_list(params, tags) return conn.get_status('AddTags', params, verb='POST')
saltstack/salt
salt/modules/pkg_resource.py
_repack_pkgs
python
def _repack_pkgs(pkgs, normalize=True): ''' Repack packages specified using "pkgs" argument to pkg states into a single dictionary ''' if normalize and 'pkg.normalize_name' in __salt__: _normalize_name = __salt__['pkg.normalize_name'] else: _normalize_name = lambda pkgname: pkgname return dict( [ (_normalize_name(six.text_type(x)), six.text_type(y) if y is not None else y) for x, y in six.iteritems(salt.utils.data.repack_dictlist(pkgs)) ] )
Repack packages specified using "pkgs" argument to pkg states into a single dictionary
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/pkg_resource.py#L27-L41
null
# -*- coding: utf-8 -*- ''' Resources needed by pkg providers ''' # Import python libs from __future__ import absolute_import, print_function, unicode_literals import copy import fnmatch import logging import os import pprint # Import third party libs from salt.ext import six # Import salt libs import salt.utils.data import salt.utils.versions import salt.utils.yaml from salt.exceptions import SaltInvocationError log = logging.getLogger(__name__) __SUFFIX_NOT_NEEDED = ('x86_64', 'noarch') def pack_sources(sources, normalize=True): ''' Accepts list of dicts (or a string representing a list of dicts) and packs the key/value pairs into a single dict. ``'[{"foo": "salt://foo.rpm"}, {"bar": "salt://bar.rpm"}]'`` would become ``{"foo": "salt://foo.rpm", "bar": "salt://bar.rpm"}`` normalize : True Normalize the package name by removing the architecture, if the architecture of the package is different from the architecture of the operating system. The ability to disable this behavior is useful for poorly-created packages which include the architecture as an actual part of the name, such as kernel modules which match a specific kernel version. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt '*' pkg_resource.pack_sources '[{"foo": "salt://foo.rpm"}, {"bar": "salt://bar.rpm"}]' ''' if normalize and 'pkg.normalize_name' in __salt__: _normalize_name = __salt__['pkg.normalize_name'] else: _normalize_name = lambda pkgname: pkgname if isinstance(sources, six.string_types): try: sources = salt.utils.yaml.safe_load(sources) except salt.utils.yaml.parser.ParserError as err: log.error(err) return {} ret = {} for source in sources: if (not isinstance(source, dict)) or len(source) != 1: log.error('Invalid input: %s', pprint.pformat(sources)) log.error('Input must be a list of 1-element dicts') return {} else: key = next(iter(source)) ret[_normalize_name(key)] = source[key] return ret def parse_targets(name=None, pkgs=None, sources=None, saltenv='base', normalize=True, **kwargs): ''' Parses the input to pkg.install and returns back the package(s) to be installed. Returns a list of packages, as well as a string noting whether the packages are to come from a repository or a binary package. CLI Example: .. code-block:: bash salt '*' pkg_resource.parse_targets ''' if '__env__' in kwargs: # "env" is not supported; Use "saltenv". kwargs.pop('__env__') if __grains__['os'] == 'MacOS' and sources: log.warning('Parameter "sources" ignored on MacOS hosts.') version = kwargs.get('version') if pkgs and sources: log.error('Only one of "pkgs" and "sources" can be used.') return None, None elif 'advisory_ids' in kwargs: if pkgs: log.error('Cannot use "advisory_ids" and "pkgs" at the same time') return None, None elif kwargs['advisory_ids']: return kwargs['advisory_ids'], 'advisory' else: return [name], 'advisory' elif pkgs: if version is not None: log.warning('\'version\' argument will be ignored for multiple ' 'package targets') pkgs = _repack_pkgs(pkgs, normalize=normalize) if not pkgs: return None, None else: return pkgs, 'repository' elif sources and __grains__['os'] != 'MacOS': if version is not None: log.warning('\'version\' argument will be ignored for multiple ' 'package targets') sources = pack_sources(sources, normalize=normalize) if not sources: return None, None srcinfo = [] for pkg_name, pkg_src in six.iteritems(sources): if __salt__['config.valid_fileproto'](pkg_src): # Cache package from remote source (salt master, HTTP, FTP) and # append the cached path. srcinfo.append(__salt__['cp.cache_file'](pkg_src, saltenv)) else: # Package file local to the minion, just append the path to the # package file. if not os.path.isabs(pkg_src): raise SaltInvocationError( 'Path {0} for package {1} is either not absolute or ' 'an invalid protocol'.format(pkg_src, pkg_name) ) srcinfo.append(pkg_src) return srcinfo, 'file' elif name: if normalize: _normalize_name = \ __salt__.get('pkg.normalize_name', lambda pkgname: pkgname) packed = dict([(_normalize_name(x), version) for x in name.split(',')]) else: packed = dict([(x, version) for x in name.split(',')]) return packed, 'repository' else: log.error('No package sources provided') return None, None def version(*names, **kwargs): ''' Common interface for obtaining the version of installed packages. CLI Example: .. code-block:: bash salt '*' pkg_resource.version vim salt '*' pkg_resource.version foo bar baz salt '*' pkg_resource.version 'python*' ''' ret = {} versions_as_list = \ salt.utils.data.is_true(kwargs.pop('versions_as_list', False)) pkg_glob = False if names: pkgs = __salt__['pkg.list_pkgs'](versions_as_list=True, **kwargs) for name in names: if '*' in name: pkg_glob = True for match in fnmatch.filter(pkgs, name): ret[match] = pkgs.get(match, []) else: ret[name] = pkgs.get(name, []) if not versions_as_list: __salt__['pkg_resource.stringify'](ret) # Return a string if no globbing is used, and there is one item in the # return dict if len(ret) == 1 and not pkg_glob: try: return next(six.itervalues(ret)) except StopIteration: return '' return ret def add_pkg(pkgs, name, pkgver): ''' Add a package to a dict of installed packages. CLI Example: .. code-block:: bash salt '*' pkg_resource.add_pkg '{}' bind 9 ''' try: pkgs.setdefault(name, []).append(pkgver) except AttributeError as exc: log.exception(exc) def sort_pkglist(pkgs): ''' Accepts a dict obtained from pkg.list_pkgs() and sorts in place the list of versions for any packages that have multiple versions installed, so that two package lists can be compared to one another. CLI Example: .. code-block:: bash salt '*' pkg_resource.sort_pkglist '["3.45", "2.13"]' ''' # It doesn't matter that ['4.9','4.10'] would be sorted to ['4.10','4.9'], # so long as the sorting is consistent. try: for key in pkgs: # Passing the pkglist to set() also removes duplicate version # numbers (if present). pkgs[key] = sorted(set(pkgs[key])) except AttributeError as exc: log.exception(exc) def stringify(pkgs): ''' Takes a dict of package name/version information and joins each list of installed versions into a string. CLI Example: .. code-block:: bash salt '*' pkg_resource.stringify 'vim: 7.127' ''' try: for key in pkgs: pkgs[key] = ','.join(pkgs[key]) except AttributeError as exc: log.exception(exc) def version_clean(verstr): ''' Clean the version string removing extra data. This function will simply try to call ``pkg.version_clean``. CLI Example: .. code-block:: bash salt '*' pkg_resource.version_clean <version_string> ''' if verstr and 'pkg.version_clean' in __salt__: return __salt__['pkg.version_clean'](verstr) return verstr def check_extra_requirements(pkgname, pkgver): ''' Check if the installed package already has the given requirements. This function will return the result of ``pkg.check_extra_requirements`` if this function exists for the minion, otherwise it will return True. CLI Example: .. code-block:: bash salt '*' pkg_resource.check_extra_requirements <pkgname> <extra_requirements> ''' if pkgver and 'pkg.check_extra_requirements' in __salt__: return __salt__['pkg.check_extra_requirements'](pkgname, pkgver) return True def format_pkg_list(packages, versions_as_list, attr): ''' Formats packages according to parameters for list_pkgs. ''' ret = copy.deepcopy(packages) if attr: requested_attr = {'epoch', 'version', 'release', 'arch', 'install_date', 'install_date_time_t'} if attr != 'all': requested_attr &= set(attr + ['version']) for name in ret: versions = [] for all_attr in ret[name]: filtered_attr = {} for key in requested_attr: if all_attr[key]: filtered_attr[key] = all_attr[key] versions.append(filtered_attr) ret[name] = versions return ret for name in ret: ret[name] = [format_version(d['epoch'], d['version'], d['release']) for d in ret[name]] if not versions_as_list: stringify(ret) return ret def format_version(epoch, version, release): ''' Formats a version string for list_pkgs. ''' full_version = '{0}:{1}'.format(epoch, version) if epoch else version if release: full_version += '-{0}'.format(release) return full_version
saltstack/salt
salt/modules/pkg_resource.py
pack_sources
python
def pack_sources(sources, normalize=True): ''' Accepts list of dicts (or a string representing a list of dicts) and packs the key/value pairs into a single dict. ``'[{"foo": "salt://foo.rpm"}, {"bar": "salt://bar.rpm"}]'`` would become ``{"foo": "salt://foo.rpm", "bar": "salt://bar.rpm"}`` normalize : True Normalize the package name by removing the architecture, if the architecture of the package is different from the architecture of the operating system. The ability to disable this behavior is useful for poorly-created packages which include the architecture as an actual part of the name, such as kernel modules which match a specific kernel version. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt '*' pkg_resource.pack_sources '[{"foo": "salt://foo.rpm"}, {"bar": "salt://bar.rpm"}]' ''' if normalize and 'pkg.normalize_name' in __salt__: _normalize_name = __salt__['pkg.normalize_name'] else: _normalize_name = lambda pkgname: pkgname if isinstance(sources, six.string_types): try: sources = salt.utils.yaml.safe_load(sources) except salt.utils.yaml.parser.ParserError as err: log.error(err) return {} ret = {} for source in sources: if (not isinstance(source, dict)) or len(source) != 1: log.error('Invalid input: %s', pprint.pformat(sources)) log.error('Input must be a list of 1-element dicts') return {} else: key = next(iter(source)) ret[_normalize_name(key)] = source[key] return ret
Accepts list of dicts (or a string representing a list of dicts) and packs the key/value pairs into a single dict. ``'[{"foo": "salt://foo.rpm"}, {"bar": "salt://bar.rpm"}]'`` would become ``{"foo": "salt://foo.rpm", "bar": "salt://bar.rpm"}`` normalize : True Normalize the package name by removing the architecture, if the architecture of the package is different from the architecture of the operating system. The ability to disable this behavior is useful for poorly-created packages which include the architecture as an actual part of the name, such as kernel modules which match a specific kernel version. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt '*' pkg_resource.pack_sources '[{"foo": "salt://foo.rpm"}, {"bar": "salt://bar.rpm"}]'
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/pkg_resource.py#L44-L88
[ "def safe_load(stream, Loader=SaltYamlSafeLoader):\n '''\n .. versionadded:: 2018.3.0\n\n Helper function which automagically uses our custom loader.\n '''\n return yaml.load(stream, Loader=Loader)\n", "_normalize_name = lambda pkgname: pkgname\n" ]
# -*- coding: utf-8 -*- ''' Resources needed by pkg providers ''' # Import python libs from __future__ import absolute_import, print_function, unicode_literals import copy import fnmatch import logging import os import pprint # Import third party libs from salt.ext import six # Import salt libs import salt.utils.data import salt.utils.versions import salt.utils.yaml from salt.exceptions import SaltInvocationError log = logging.getLogger(__name__) __SUFFIX_NOT_NEEDED = ('x86_64', 'noarch') def _repack_pkgs(pkgs, normalize=True): ''' Repack packages specified using "pkgs" argument to pkg states into a single dictionary ''' if normalize and 'pkg.normalize_name' in __salt__: _normalize_name = __salt__['pkg.normalize_name'] else: _normalize_name = lambda pkgname: pkgname return dict( [ (_normalize_name(six.text_type(x)), six.text_type(y) if y is not None else y) for x, y in six.iteritems(salt.utils.data.repack_dictlist(pkgs)) ] ) def parse_targets(name=None, pkgs=None, sources=None, saltenv='base', normalize=True, **kwargs): ''' Parses the input to pkg.install and returns back the package(s) to be installed. Returns a list of packages, as well as a string noting whether the packages are to come from a repository or a binary package. CLI Example: .. code-block:: bash salt '*' pkg_resource.parse_targets ''' if '__env__' in kwargs: # "env" is not supported; Use "saltenv". kwargs.pop('__env__') if __grains__['os'] == 'MacOS' and sources: log.warning('Parameter "sources" ignored on MacOS hosts.') version = kwargs.get('version') if pkgs and sources: log.error('Only one of "pkgs" and "sources" can be used.') return None, None elif 'advisory_ids' in kwargs: if pkgs: log.error('Cannot use "advisory_ids" and "pkgs" at the same time') return None, None elif kwargs['advisory_ids']: return kwargs['advisory_ids'], 'advisory' else: return [name], 'advisory' elif pkgs: if version is not None: log.warning('\'version\' argument will be ignored for multiple ' 'package targets') pkgs = _repack_pkgs(pkgs, normalize=normalize) if not pkgs: return None, None else: return pkgs, 'repository' elif sources and __grains__['os'] != 'MacOS': if version is not None: log.warning('\'version\' argument will be ignored for multiple ' 'package targets') sources = pack_sources(sources, normalize=normalize) if not sources: return None, None srcinfo = [] for pkg_name, pkg_src in six.iteritems(sources): if __salt__['config.valid_fileproto'](pkg_src): # Cache package from remote source (salt master, HTTP, FTP) and # append the cached path. srcinfo.append(__salt__['cp.cache_file'](pkg_src, saltenv)) else: # Package file local to the minion, just append the path to the # package file. if not os.path.isabs(pkg_src): raise SaltInvocationError( 'Path {0} for package {1} is either not absolute or ' 'an invalid protocol'.format(pkg_src, pkg_name) ) srcinfo.append(pkg_src) return srcinfo, 'file' elif name: if normalize: _normalize_name = \ __salt__.get('pkg.normalize_name', lambda pkgname: pkgname) packed = dict([(_normalize_name(x), version) for x in name.split(',')]) else: packed = dict([(x, version) for x in name.split(',')]) return packed, 'repository' else: log.error('No package sources provided') return None, None def version(*names, **kwargs): ''' Common interface for obtaining the version of installed packages. CLI Example: .. code-block:: bash salt '*' pkg_resource.version vim salt '*' pkg_resource.version foo bar baz salt '*' pkg_resource.version 'python*' ''' ret = {} versions_as_list = \ salt.utils.data.is_true(kwargs.pop('versions_as_list', False)) pkg_glob = False if names: pkgs = __salt__['pkg.list_pkgs'](versions_as_list=True, **kwargs) for name in names: if '*' in name: pkg_glob = True for match in fnmatch.filter(pkgs, name): ret[match] = pkgs.get(match, []) else: ret[name] = pkgs.get(name, []) if not versions_as_list: __salt__['pkg_resource.stringify'](ret) # Return a string if no globbing is used, and there is one item in the # return dict if len(ret) == 1 and not pkg_glob: try: return next(six.itervalues(ret)) except StopIteration: return '' return ret def add_pkg(pkgs, name, pkgver): ''' Add a package to a dict of installed packages. CLI Example: .. code-block:: bash salt '*' pkg_resource.add_pkg '{}' bind 9 ''' try: pkgs.setdefault(name, []).append(pkgver) except AttributeError as exc: log.exception(exc) def sort_pkglist(pkgs): ''' Accepts a dict obtained from pkg.list_pkgs() and sorts in place the list of versions for any packages that have multiple versions installed, so that two package lists can be compared to one another. CLI Example: .. code-block:: bash salt '*' pkg_resource.sort_pkglist '["3.45", "2.13"]' ''' # It doesn't matter that ['4.9','4.10'] would be sorted to ['4.10','4.9'], # so long as the sorting is consistent. try: for key in pkgs: # Passing the pkglist to set() also removes duplicate version # numbers (if present). pkgs[key] = sorted(set(pkgs[key])) except AttributeError as exc: log.exception(exc) def stringify(pkgs): ''' Takes a dict of package name/version information and joins each list of installed versions into a string. CLI Example: .. code-block:: bash salt '*' pkg_resource.stringify 'vim: 7.127' ''' try: for key in pkgs: pkgs[key] = ','.join(pkgs[key]) except AttributeError as exc: log.exception(exc) def version_clean(verstr): ''' Clean the version string removing extra data. This function will simply try to call ``pkg.version_clean``. CLI Example: .. code-block:: bash salt '*' pkg_resource.version_clean <version_string> ''' if verstr and 'pkg.version_clean' in __salt__: return __salt__['pkg.version_clean'](verstr) return verstr def check_extra_requirements(pkgname, pkgver): ''' Check if the installed package already has the given requirements. This function will return the result of ``pkg.check_extra_requirements`` if this function exists for the minion, otherwise it will return True. CLI Example: .. code-block:: bash salt '*' pkg_resource.check_extra_requirements <pkgname> <extra_requirements> ''' if pkgver and 'pkg.check_extra_requirements' in __salt__: return __salt__['pkg.check_extra_requirements'](pkgname, pkgver) return True def format_pkg_list(packages, versions_as_list, attr): ''' Formats packages according to parameters for list_pkgs. ''' ret = copy.deepcopy(packages) if attr: requested_attr = {'epoch', 'version', 'release', 'arch', 'install_date', 'install_date_time_t'} if attr != 'all': requested_attr &= set(attr + ['version']) for name in ret: versions = [] for all_attr in ret[name]: filtered_attr = {} for key in requested_attr: if all_attr[key]: filtered_attr[key] = all_attr[key] versions.append(filtered_attr) ret[name] = versions return ret for name in ret: ret[name] = [format_version(d['epoch'], d['version'], d['release']) for d in ret[name]] if not versions_as_list: stringify(ret) return ret def format_version(epoch, version, release): ''' Formats a version string for list_pkgs. ''' full_version = '{0}:{1}'.format(epoch, version) if epoch else version if release: full_version += '-{0}'.format(release) return full_version
saltstack/salt
salt/modules/pkg_resource.py
parse_targets
python
def parse_targets(name=None, pkgs=None, sources=None, saltenv='base', normalize=True, **kwargs): ''' Parses the input to pkg.install and returns back the package(s) to be installed. Returns a list of packages, as well as a string noting whether the packages are to come from a repository or a binary package. CLI Example: .. code-block:: bash salt '*' pkg_resource.parse_targets ''' if '__env__' in kwargs: # "env" is not supported; Use "saltenv". kwargs.pop('__env__') if __grains__['os'] == 'MacOS' and sources: log.warning('Parameter "sources" ignored on MacOS hosts.') version = kwargs.get('version') if pkgs and sources: log.error('Only one of "pkgs" and "sources" can be used.') return None, None elif 'advisory_ids' in kwargs: if pkgs: log.error('Cannot use "advisory_ids" and "pkgs" at the same time') return None, None elif kwargs['advisory_ids']: return kwargs['advisory_ids'], 'advisory' else: return [name], 'advisory' elif pkgs: if version is not None: log.warning('\'version\' argument will be ignored for multiple ' 'package targets') pkgs = _repack_pkgs(pkgs, normalize=normalize) if not pkgs: return None, None else: return pkgs, 'repository' elif sources and __grains__['os'] != 'MacOS': if version is not None: log.warning('\'version\' argument will be ignored for multiple ' 'package targets') sources = pack_sources(sources, normalize=normalize) if not sources: return None, None srcinfo = [] for pkg_name, pkg_src in six.iteritems(sources): if __salt__['config.valid_fileproto'](pkg_src): # Cache package from remote source (salt master, HTTP, FTP) and # append the cached path. srcinfo.append(__salt__['cp.cache_file'](pkg_src, saltenv)) else: # Package file local to the minion, just append the path to the # package file. if not os.path.isabs(pkg_src): raise SaltInvocationError( 'Path {0} for package {1} is either not absolute or ' 'an invalid protocol'.format(pkg_src, pkg_name) ) srcinfo.append(pkg_src) return srcinfo, 'file' elif name: if normalize: _normalize_name = \ __salt__.get('pkg.normalize_name', lambda pkgname: pkgname) packed = dict([(_normalize_name(x), version) for x in name.split(',')]) else: packed = dict([(x, version) for x in name.split(',')]) return packed, 'repository' else: log.error('No package sources provided') return None, None
Parses the input to pkg.install and returns back the package(s) to be installed. Returns a list of packages, as well as a string noting whether the packages are to come from a repository or a binary package. CLI Example: .. code-block:: bash salt '*' pkg_resource.parse_targets
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/pkg_resource.py#L91-L177
[ "def iteritems(d, **kw):\n return d.iteritems(**kw)\n", "def _repack_pkgs(pkgs, normalize=True):\n '''\n Repack packages specified using \"pkgs\" argument to pkg states into a single\n dictionary\n '''\n if normalize and 'pkg.normalize_name' in __salt__:\n _normalize_name = __salt__['pkg.normalize_name']\n else:\n _normalize_name = lambda pkgname: pkgname\n return dict(\n [\n (_normalize_name(six.text_type(x)), six.text_type(y) if y is not None else y)\n for x, y in six.iteritems(salt.utils.data.repack_dictlist(pkgs))\n ]\n )\n", "def pack_sources(sources, normalize=True):\n '''\n Accepts list of dicts (or a string representing a list of dicts) and packs\n the key/value pairs into a single dict.\n\n ``'[{\"foo\": \"salt://foo.rpm\"}, {\"bar\": \"salt://bar.rpm\"}]'`` would become\n ``{\"foo\": \"salt://foo.rpm\", \"bar\": \"salt://bar.rpm\"}``\n\n normalize : True\n Normalize the package name by removing the architecture, if the\n architecture of the package is different from the architecture of the\n operating system. The ability to disable this behavior is useful for\n poorly-created packages which include the architecture as an actual\n part of the name, such as kernel modules which match a specific kernel\n version.\n\n .. versionadded:: 2015.8.0\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' pkg_resource.pack_sources '[{\"foo\": \"salt://foo.rpm\"}, {\"bar\": \"salt://bar.rpm\"}]'\n '''\n if normalize and 'pkg.normalize_name' in __salt__:\n _normalize_name = __salt__['pkg.normalize_name']\n else:\n _normalize_name = lambda pkgname: pkgname\n\n if isinstance(sources, six.string_types):\n try:\n sources = salt.utils.yaml.safe_load(sources)\n except salt.utils.yaml.parser.ParserError as err:\n log.error(err)\n return {}\n ret = {}\n for source in sources:\n if (not isinstance(source, dict)) or len(source) != 1:\n log.error('Invalid input: %s', pprint.pformat(sources))\n log.error('Input must be a list of 1-element dicts')\n return {}\n else:\n key = next(iter(source))\n ret[_normalize_name(key)] = source[key]\n return ret\n" ]
# -*- coding: utf-8 -*- ''' Resources needed by pkg providers ''' # Import python libs from __future__ import absolute_import, print_function, unicode_literals import copy import fnmatch import logging import os import pprint # Import third party libs from salt.ext import six # Import salt libs import salt.utils.data import salt.utils.versions import salt.utils.yaml from salt.exceptions import SaltInvocationError log = logging.getLogger(__name__) __SUFFIX_NOT_NEEDED = ('x86_64', 'noarch') def _repack_pkgs(pkgs, normalize=True): ''' Repack packages specified using "pkgs" argument to pkg states into a single dictionary ''' if normalize and 'pkg.normalize_name' in __salt__: _normalize_name = __salt__['pkg.normalize_name'] else: _normalize_name = lambda pkgname: pkgname return dict( [ (_normalize_name(six.text_type(x)), six.text_type(y) if y is not None else y) for x, y in six.iteritems(salt.utils.data.repack_dictlist(pkgs)) ] ) def pack_sources(sources, normalize=True): ''' Accepts list of dicts (or a string representing a list of dicts) and packs the key/value pairs into a single dict. ``'[{"foo": "salt://foo.rpm"}, {"bar": "salt://bar.rpm"}]'`` would become ``{"foo": "salt://foo.rpm", "bar": "salt://bar.rpm"}`` normalize : True Normalize the package name by removing the architecture, if the architecture of the package is different from the architecture of the operating system. The ability to disable this behavior is useful for poorly-created packages which include the architecture as an actual part of the name, such as kernel modules which match a specific kernel version. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt '*' pkg_resource.pack_sources '[{"foo": "salt://foo.rpm"}, {"bar": "salt://bar.rpm"}]' ''' if normalize and 'pkg.normalize_name' in __salt__: _normalize_name = __salt__['pkg.normalize_name'] else: _normalize_name = lambda pkgname: pkgname if isinstance(sources, six.string_types): try: sources = salt.utils.yaml.safe_load(sources) except salt.utils.yaml.parser.ParserError as err: log.error(err) return {} ret = {} for source in sources: if (not isinstance(source, dict)) or len(source) != 1: log.error('Invalid input: %s', pprint.pformat(sources)) log.error('Input must be a list of 1-element dicts') return {} else: key = next(iter(source)) ret[_normalize_name(key)] = source[key] return ret def version(*names, **kwargs): ''' Common interface for obtaining the version of installed packages. CLI Example: .. code-block:: bash salt '*' pkg_resource.version vim salt '*' pkg_resource.version foo bar baz salt '*' pkg_resource.version 'python*' ''' ret = {} versions_as_list = \ salt.utils.data.is_true(kwargs.pop('versions_as_list', False)) pkg_glob = False if names: pkgs = __salt__['pkg.list_pkgs'](versions_as_list=True, **kwargs) for name in names: if '*' in name: pkg_glob = True for match in fnmatch.filter(pkgs, name): ret[match] = pkgs.get(match, []) else: ret[name] = pkgs.get(name, []) if not versions_as_list: __salt__['pkg_resource.stringify'](ret) # Return a string if no globbing is used, and there is one item in the # return dict if len(ret) == 1 and not pkg_glob: try: return next(six.itervalues(ret)) except StopIteration: return '' return ret def add_pkg(pkgs, name, pkgver): ''' Add a package to a dict of installed packages. CLI Example: .. code-block:: bash salt '*' pkg_resource.add_pkg '{}' bind 9 ''' try: pkgs.setdefault(name, []).append(pkgver) except AttributeError as exc: log.exception(exc) def sort_pkglist(pkgs): ''' Accepts a dict obtained from pkg.list_pkgs() and sorts in place the list of versions for any packages that have multiple versions installed, so that two package lists can be compared to one another. CLI Example: .. code-block:: bash salt '*' pkg_resource.sort_pkglist '["3.45", "2.13"]' ''' # It doesn't matter that ['4.9','4.10'] would be sorted to ['4.10','4.9'], # so long as the sorting is consistent. try: for key in pkgs: # Passing the pkglist to set() also removes duplicate version # numbers (if present). pkgs[key] = sorted(set(pkgs[key])) except AttributeError as exc: log.exception(exc) def stringify(pkgs): ''' Takes a dict of package name/version information and joins each list of installed versions into a string. CLI Example: .. code-block:: bash salt '*' pkg_resource.stringify 'vim: 7.127' ''' try: for key in pkgs: pkgs[key] = ','.join(pkgs[key]) except AttributeError as exc: log.exception(exc) def version_clean(verstr): ''' Clean the version string removing extra data. This function will simply try to call ``pkg.version_clean``. CLI Example: .. code-block:: bash salt '*' pkg_resource.version_clean <version_string> ''' if verstr and 'pkg.version_clean' in __salt__: return __salt__['pkg.version_clean'](verstr) return verstr def check_extra_requirements(pkgname, pkgver): ''' Check if the installed package already has the given requirements. This function will return the result of ``pkg.check_extra_requirements`` if this function exists for the minion, otherwise it will return True. CLI Example: .. code-block:: bash salt '*' pkg_resource.check_extra_requirements <pkgname> <extra_requirements> ''' if pkgver and 'pkg.check_extra_requirements' in __salt__: return __salt__['pkg.check_extra_requirements'](pkgname, pkgver) return True def format_pkg_list(packages, versions_as_list, attr): ''' Formats packages according to parameters for list_pkgs. ''' ret = copy.deepcopy(packages) if attr: requested_attr = {'epoch', 'version', 'release', 'arch', 'install_date', 'install_date_time_t'} if attr != 'all': requested_attr &= set(attr + ['version']) for name in ret: versions = [] for all_attr in ret[name]: filtered_attr = {} for key in requested_attr: if all_attr[key]: filtered_attr[key] = all_attr[key] versions.append(filtered_attr) ret[name] = versions return ret for name in ret: ret[name] = [format_version(d['epoch'], d['version'], d['release']) for d in ret[name]] if not versions_as_list: stringify(ret) return ret def format_version(epoch, version, release): ''' Formats a version string for list_pkgs. ''' full_version = '{0}:{1}'.format(epoch, version) if epoch else version if release: full_version += '-{0}'.format(release) return full_version
saltstack/salt
salt/modules/pkg_resource.py
version
python
def version(*names, **kwargs): ''' Common interface for obtaining the version of installed packages. CLI Example: .. code-block:: bash salt '*' pkg_resource.version vim salt '*' pkg_resource.version foo bar baz salt '*' pkg_resource.version 'python*' ''' ret = {} versions_as_list = \ salt.utils.data.is_true(kwargs.pop('versions_as_list', False)) pkg_glob = False if names: pkgs = __salt__['pkg.list_pkgs'](versions_as_list=True, **kwargs) for name in names: if '*' in name: pkg_glob = True for match in fnmatch.filter(pkgs, name): ret[match] = pkgs.get(match, []) else: ret[name] = pkgs.get(name, []) if not versions_as_list: __salt__['pkg_resource.stringify'](ret) # Return a string if no globbing is used, and there is one item in the # return dict if len(ret) == 1 and not pkg_glob: try: return next(six.itervalues(ret)) except StopIteration: return '' return ret
Common interface for obtaining the version of installed packages. CLI Example: .. code-block:: bash salt '*' pkg_resource.version vim salt '*' pkg_resource.version foo bar baz salt '*' pkg_resource.version 'python*'
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/pkg_resource.py#L180-L214
[ "def itervalues(d, **kw):\n return d.itervalues(**kw)\n", "def is_true(value=None):\n '''\n Returns a boolean value representing the \"truth\" of the value passed. The\n rules for what is a \"True\" value are:\n\n 1. Integer/float values greater than 0\n 2. The string values \"True\" and \"true\"\n 3. Any object for which bool(obj) returns True\n '''\n # First, try int/float conversion\n try:\n value = int(value)\n except (ValueError, TypeError):\n pass\n try:\n value = float(value)\n except (ValueError, TypeError):\n pass\n\n # Now check for truthiness\n if isinstance(value, (six.integer_types, float)):\n return value > 0\n elif isinstance(value, six.string_types):\n return six.text_type(value).lower() == 'true'\n else:\n return bool(value)\n" ]
# -*- coding: utf-8 -*- ''' Resources needed by pkg providers ''' # Import python libs from __future__ import absolute_import, print_function, unicode_literals import copy import fnmatch import logging import os import pprint # Import third party libs from salt.ext import six # Import salt libs import salt.utils.data import salt.utils.versions import salt.utils.yaml from salt.exceptions import SaltInvocationError log = logging.getLogger(__name__) __SUFFIX_NOT_NEEDED = ('x86_64', 'noarch') def _repack_pkgs(pkgs, normalize=True): ''' Repack packages specified using "pkgs" argument to pkg states into a single dictionary ''' if normalize and 'pkg.normalize_name' in __salt__: _normalize_name = __salt__['pkg.normalize_name'] else: _normalize_name = lambda pkgname: pkgname return dict( [ (_normalize_name(six.text_type(x)), six.text_type(y) if y is not None else y) for x, y in six.iteritems(salt.utils.data.repack_dictlist(pkgs)) ] ) def pack_sources(sources, normalize=True): ''' Accepts list of dicts (or a string representing a list of dicts) and packs the key/value pairs into a single dict. ``'[{"foo": "salt://foo.rpm"}, {"bar": "salt://bar.rpm"}]'`` would become ``{"foo": "salt://foo.rpm", "bar": "salt://bar.rpm"}`` normalize : True Normalize the package name by removing the architecture, if the architecture of the package is different from the architecture of the operating system. The ability to disable this behavior is useful for poorly-created packages which include the architecture as an actual part of the name, such as kernel modules which match a specific kernel version. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt '*' pkg_resource.pack_sources '[{"foo": "salt://foo.rpm"}, {"bar": "salt://bar.rpm"}]' ''' if normalize and 'pkg.normalize_name' in __salt__: _normalize_name = __salt__['pkg.normalize_name'] else: _normalize_name = lambda pkgname: pkgname if isinstance(sources, six.string_types): try: sources = salt.utils.yaml.safe_load(sources) except salt.utils.yaml.parser.ParserError as err: log.error(err) return {} ret = {} for source in sources: if (not isinstance(source, dict)) or len(source) != 1: log.error('Invalid input: %s', pprint.pformat(sources)) log.error('Input must be a list of 1-element dicts') return {} else: key = next(iter(source)) ret[_normalize_name(key)] = source[key] return ret def parse_targets(name=None, pkgs=None, sources=None, saltenv='base', normalize=True, **kwargs): ''' Parses the input to pkg.install and returns back the package(s) to be installed. Returns a list of packages, as well as a string noting whether the packages are to come from a repository or a binary package. CLI Example: .. code-block:: bash salt '*' pkg_resource.parse_targets ''' if '__env__' in kwargs: # "env" is not supported; Use "saltenv". kwargs.pop('__env__') if __grains__['os'] == 'MacOS' and sources: log.warning('Parameter "sources" ignored on MacOS hosts.') version = kwargs.get('version') if pkgs and sources: log.error('Only one of "pkgs" and "sources" can be used.') return None, None elif 'advisory_ids' in kwargs: if pkgs: log.error('Cannot use "advisory_ids" and "pkgs" at the same time') return None, None elif kwargs['advisory_ids']: return kwargs['advisory_ids'], 'advisory' else: return [name], 'advisory' elif pkgs: if version is not None: log.warning('\'version\' argument will be ignored for multiple ' 'package targets') pkgs = _repack_pkgs(pkgs, normalize=normalize) if not pkgs: return None, None else: return pkgs, 'repository' elif sources and __grains__['os'] != 'MacOS': if version is not None: log.warning('\'version\' argument will be ignored for multiple ' 'package targets') sources = pack_sources(sources, normalize=normalize) if not sources: return None, None srcinfo = [] for pkg_name, pkg_src in six.iteritems(sources): if __salt__['config.valid_fileproto'](pkg_src): # Cache package from remote source (salt master, HTTP, FTP) and # append the cached path. srcinfo.append(__salt__['cp.cache_file'](pkg_src, saltenv)) else: # Package file local to the minion, just append the path to the # package file. if not os.path.isabs(pkg_src): raise SaltInvocationError( 'Path {0} for package {1} is either not absolute or ' 'an invalid protocol'.format(pkg_src, pkg_name) ) srcinfo.append(pkg_src) return srcinfo, 'file' elif name: if normalize: _normalize_name = \ __salt__.get('pkg.normalize_name', lambda pkgname: pkgname) packed = dict([(_normalize_name(x), version) for x in name.split(',')]) else: packed = dict([(x, version) for x in name.split(',')]) return packed, 'repository' else: log.error('No package sources provided') return None, None def add_pkg(pkgs, name, pkgver): ''' Add a package to a dict of installed packages. CLI Example: .. code-block:: bash salt '*' pkg_resource.add_pkg '{}' bind 9 ''' try: pkgs.setdefault(name, []).append(pkgver) except AttributeError as exc: log.exception(exc) def sort_pkglist(pkgs): ''' Accepts a dict obtained from pkg.list_pkgs() and sorts in place the list of versions for any packages that have multiple versions installed, so that two package lists can be compared to one another. CLI Example: .. code-block:: bash salt '*' pkg_resource.sort_pkglist '["3.45", "2.13"]' ''' # It doesn't matter that ['4.9','4.10'] would be sorted to ['4.10','4.9'], # so long as the sorting is consistent. try: for key in pkgs: # Passing the pkglist to set() also removes duplicate version # numbers (if present). pkgs[key] = sorted(set(pkgs[key])) except AttributeError as exc: log.exception(exc) def stringify(pkgs): ''' Takes a dict of package name/version information and joins each list of installed versions into a string. CLI Example: .. code-block:: bash salt '*' pkg_resource.stringify 'vim: 7.127' ''' try: for key in pkgs: pkgs[key] = ','.join(pkgs[key]) except AttributeError as exc: log.exception(exc) def version_clean(verstr): ''' Clean the version string removing extra data. This function will simply try to call ``pkg.version_clean``. CLI Example: .. code-block:: bash salt '*' pkg_resource.version_clean <version_string> ''' if verstr and 'pkg.version_clean' in __salt__: return __salt__['pkg.version_clean'](verstr) return verstr def check_extra_requirements(pkgname, pkgver): ''' Check if the installed package already has the given requirements. This function will return the result of ``pkg.check_extra_requirements`` if this function exists for the minion, otherwise it will return True. CLI Example: .. code-block:: bash salt '*' pkg_resource.check_extra_requirements <pkgname> <extra_requirements> ''' if pkgver and 'pkg.check_extra_requirements' in __salt__: return __salt__['pkg.check_extra_requirements'](pkgname, pkgver) return True def format_pkg_list(packages, versions_as_list, attr): ''' Formats packages according to parameters for list_pkgs. ''' ret = copy.deepcopy(packages) if attr: requested_attr = {'epoch', 'version', 'release', 'arch', 'install_date', 'install_date_time_t'} if attr != 'all': requested_attr &= set(attr + ['version']) for name in ret: versions = [] for all_attr in ret[name]: filtered_attr = {} for key in requested_attr: if all_attr[key]: filtered_attr[key] = all_attr[key] versions.append(filtered_attr) ret[name] = versions return ret for name in ret: ret[name] = [format_version(d['epoch'], d['version'], d['release']) for d in ret[name]] if not versions_as_list: stringify(ret) return ret def format_version(epoch, version, release): ''' Formats a version string for list_pkgs. ''' full_version = '{0}:{1}'.format(epoch, version) if epoch else version if release: full_version += '-{0}'.format(release) return full_version
saltstack/salt
salt/modules/pkg_resource.py
add_pkg
python
def add_pkg(pkgs, name, pkgver): ''' Add a package to a dict of installed packages. CLI Example: .. code-block:: bash salt '*' pkg_resource.add_pkg '{}' bind 9 ''' try: pkgs.setdefault(name, []).append(pkgver) except AttributeError as exc: log.exception(exc)
Add a package to a dict of installed packages. CLI Example: .. code-block:: bash salt '*' pkg_resource.add_pkg '{}' bind 9
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/pkg_resource.py#L217-L230
null
# -*- coding: utf-8 -*- ''' Resources needed by pkg providers ''' # Import python libs from __future__ import absolute_import, print_function, unicode_literals import copy import fnmatch import logging import os import pprint # Import third party libs from salt.ext import six # Import salt libs import salt.utils.data import salt.utils.versions import salt.utils.yaml from salt.exceptions import SaltInvocationError log = logging.getLogger(__name__) __SUFFIX_NOT_NEEDED = ('x86_64', 'noarch') def _repack_pkgs(pkgs, normalize=True): ''' Repack packages specified using "pkgs" argument to pkg states into a single dictionary ''' if normalize and 'pkg.normalize_name' in __salt__: _normalize_name = __salt__['pkg.normalize_name'] else: _normalize_name = lambda pkgname: pkgname return dict( [ (_normalize_name(six.text_type(x)), six.text_type(y) if y is not None else y) for x, y in six.iteritems(salt.utils.data.repack_dictlist(pkgs)) ] ) def pack_sources(sources, normalize=True): ''' Accepts list of dicts (or a string representing a list of dicts) and packs the key/value pairs into a single dict. ``'[{"foo": "salt://foo.rpm"}, {"bar": "salt://bar.rpm"}]'`` would become ``{"foo": "salt://foo.rpm", "bar": "salt://bar.rpm"}`` normalize : True Normalize the package name by removing the architecture, if the architecture of the package is different from the architecture of the operating system. The ability to disable this behavior is useful for poorly-created packages which include the architecture as an actual part of the name, such as kernel modules which match a specific kernel version. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt '*' pkg_resource.pack_sources '[{"foo": "salt://foo.rpm"}, {"bar": "salt://bar.rpm"}]' ''' if normalize and 'pkg.normalize_name' in __salt__: _normalize_name = __salt__['pkg.normalize_name'] else: _normalize_name = lambda pkgname: pkgname if isinstance(sources, six.string_types): try: sources = salt.utils.yaml.safe_load(sources) except salt.utils.yaml.parser.ParserError as err: log.error(err) return {} ret = {} for source in sources: if (not isinstance(source, dict)) or len(source) != 1: log.error('Invalid input: %s', pprint.pformat(sources)) log.error('Input must be a list of 1-element dicts') return {} else: key = next(iter(source)) ret[_normalize_name(key)] = source[key] return ret def parse_targets(name=None, pkgs=None, sources=None, saltenv='base', normalize=True, **kwargs): ''' Parses the input to pkg.install and returns back the package(s) to be installed. Returns a list of packages, as well as a string noting whether the packages are to come from a repository or a binary package. CLI Example: .. code-block:: bash salt '*' pkg_resource.parse_targets ''' if '__env__' in kwargs: # "env" is not supported; Use "saltenv". kwargs.pop('__env__') if __grains__['os'] == 'MacOS' and sources: log.warning('Parameter "sources" ignored on MacOS hosts.') version = kwargs.get('version') if pkgs and sources: log.error('Only one of "pkgs" and "sources" can be used.') return None, None elif 'advisory_ids' in kwargs: if pkgs: log.error('Cannot use "advisory_ids" and "pkgs" at the same time') return None, None elif kwargs['advisory_ids']: return kwargs['advisory_ids'], 'advisory' else: return [name], 'advisory' elif pkgs: if version is not None: log.warning('\'version\' argument will be ignored for multiple ' 'package targets') pkgs = _repack_pkgs(pkgs, normalize=normalize) if not pkgs: return None, None else: return pkgs, 'repository' elif sources and __grains__['os'] != 'MacOS': if version is not None: log.warning('\'version\' argument will be ignored for multiple ' 'package targets') sources = pack_sources(sources, normalize=normalize) if not sources: return None, None srcinfo = [] for pkg_name, pkg_src in six.iteritems(sources): if __salt__['config.valid_fileproto'](pkg_src): # Cache package from remote source (salt master, HTTP, FTP) and # append the cached path. srcinfo.append(__salt__['cp.cache_file'](pkg_src, saltenv)) else: # Package file local to the minion, just append the path to the # package file. if not os.path.isabs(pkg_src): raise SaltInvocationError( 'Path {0} for package {1} is either not absolute or ' 'an invalid protocol'.format(pkg_src, pkg_name) ) srcinfo.append(pkg_src) return srcinfo, 'file' elif name: if normalize: _normalize_name = \ __salt__.get('pkg.normalize_name', lambda pkgname: pkgname) packed = dict([(_normalize_name(x), version) for x in name.split(',')]) else: packed = dict([(x, version) for x in name.split(',')]) return packed, 'repository' else: log.error('No package sources provided') return None, None def version(*names, **kwargs): ''' Common interface for obtaining the version of installed packages. CLI Example: .. code-block:: bash salt '*' pkg_resource.version vim salt '*' pkg_resource.version foo bar baz salt '*' pkg_resource.version 'python*' ''' ret = {} versions_as_list = \ salt.utils.data.is_true(kwargs.pop('versions_as_list', False)) pkg_glob = False if names: pkgs = __salt__['pkg.list_pkgs'](versions_as_list=True, **kwargs) for name in names: if '*' in name: pkg_glob = True for match in fnmatch.filter(pkgs, name): ret[match] = pkgs.get(match, []) else: ret[name] = pkgs.get(name, []) if not versions_as_list: __salt__['pkg_resource.stringify'](ret) # Return a string if no globbing is used, and there is one item in the # return dict if len(ret) == 1 and not pkg_glob: try: return next(six.itervalues(ret)) except StopIteration: return '' return ret def sort_pkglist(pkgs): ''' Accepts a dict obtained from pkg.list_pkgs() and sorts in place the list of versions for any packages that have multiple versions installed, so that two package lists can be compared to one another. CLI Example: .. code-block:: bash salt '*' pkg_resource.sort_pkglist '["3.45", "2.13"]' ''' # It doesn't matter that ['4.9','4.10'] would be sorted to ['4.10','4.9'], # so long as the sorting is consistent. try: for key in pkgs: # Passing the pkglist to set() also removes duplicate version # numbers (if present). pkgs[key] = sorted(set(pkgs[key])) except AttributeError as exc: log.exception(exc) def stringify(pkgs): ''' Takes a dict of package name/version information and joins each list of installed versions into a string. CLI Example: .. code-block:: bash salt '*' pkg_resource.stringify 'vim: 7.127' ''' try: for key in pkgs: pkgs[key] = ','.join(pkgs[key]) except AttributeError as exc: log.exception(exc) def version_clean(verstr): ''' Clean the version string removing extra data. This function will simply try to call ``pkg.version_clean``. CLI Example: .. code-block:: bash salt '*' pkg_resource.version_clean <version_string> ''' if verstr and 'pkg.version_clean' in __salt__: return __salt__['pkg.version_clean'](verstr) return verstr def check_extra_requirements(pkgname, pkgver): ''' Check if the installed package already has the given requirements. This function will return the result of ``pkg.check_extra_requirements`` if this function exists for the minion, otherwise it will return True. CLI Example: .. code-block:: bash salt '*' pkg_resource.check_extra_requirements <pkgname> <extra_requirements> ''' if pkgver and 'pkg.check_extra_requirements' in __salt__: return __salt__['pkg.check_extra_requirements'](pkgname, pkgver) return True def format_pkg_list(packages, versions_as_list, attr): ''' Formats packages according to parameters for list_pkgs. ''' ret = copy.deepcopy(packages) if attr: requested_attr = {'epoch', 'version', 'release', 'arch', 'install_date', 'install_date_time_t'} if attr != 'all': requested_attr &= set(attr + ['version']) for name in ret: versions = [] for all_attr in ret[name]: filtered_attr = {} for key in requested_attr: if all_attr[key]: filtered_attr[key] = all_attr[key] versions.append(filtered_attr) ret[name] = versions return ret for name in ret: ret[name] = [format_version(d['epoch'], d['version'], d['release']) for d in ret[name]] if not versions_as_list: stringify(ret) return ret def format_version(epoch, version, release): ''' Formats a version string for list_pkgs. ''' full_version = '{0}:{1}'.format(epoch, version) if epoch else version if release: full_version += '-{0}'.format(release) return full_version
saltstack/salt
salt/modules/pkg_resource.py
sort_pkglist
python
def sort_pkglist(pkgs): ''' Accepts a dict obtained from pkg.list_pkgs() and sorts in place the list of versions for any packages that have multiple versions installed, so that two package lists can be compared to one another. CLI Example: .. code-block:: bash salt '*' pkg_resource.sort_pkglist '["3.45", "2.13"]' ''' # It doesn't matter that ['4.9','4.10'] would be sorted to ['4.10','4.9'], # so long as the sorting is consistent. try: for key in pkgs: # Passing the pkglist to set() also removes duplicate version # numbers (if present). pkgs[key] = sorted(set(pkgs[key])) except AttributeError as exc: log.exception(exc)
Accepts a dict obtained from pkg.list_pkgs() and sorts in place the list of versions for any packages that have multiple versions installed, so that two package lists can be compared to one another. CLI Example: .. code-block:: bash salt '*' pkg_resource.sort_pkglist '["3.45", "2.13"]'
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/pkg_resource.py#L233-L253
null
# -*- coding: utf-8 -*- ''' Resources needed by pkg providers ''' # Import python libs from __future__ import absolute_import, print_function, unicode_literals import copy import fnmatch import logging import os import pprint # Import third party libs from salt.ext import six # Import salt libs import salt.utils.data import salt.utils.versions import salt.utils.yaml from salt.exceptions import SaltInvocationError log = logging.getLogger(__name__) __SUFFIX_NOT_NEEDED = ('x86_64', 'noarch') def _repack_pkgs(pkgs, normalize=True): ''' Repack packages specified using "pkgs" argument to pkg states into a single dictionary ''' if normalize and 'pkg.normalize_name' in __salt__: _normalize_name = __salt__['pkg.normalize_name'] else: _normalize_name = lambda pkgname: pkgname return dict( [ (_normalize_name(six.text_type(x)), six.text_type(y) if y is not None else y) for x, y in six.iteritems(salt.utils.data.repack_dictlist(pkgs)) ] ) def pack_sources(sources, normalize=True): ''' Accepts list of dicts (or a string representing a list of dicts) and packs the key/value pairs into a single dict. ``'[{"foo": "salt://foo.rpm"}, {"bar": "salt://bar.rpm"}]'`` would become ``{"foo": "salt://foo.rpm", "bar": "salt://bar.rpm"}`` normalize : True Normalize the package name by removing the architecture, if the architecture of the package is different from the architecture of the operating system. The ability to disable this behavior is useful for poorly-created packages which include the architecture as an actual part of the name, such as kernel modules which match a specific kernel version. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt '*' pkg_resource.pack_sources '[{"foo": "salt://foo.rpm"}, {"bar": "salt://bar.rpm"}]' ''' if normalize and 'pkg.normalize_name' in __salt__: _normalize_name = __salt__['pkg.normalize_name'] else: _normalize_name = lambda pkgname: pkgname if isinstance(sources, six.string_types): try: sources = salt.utils.yaml.safe_load(sources) except salt.utils.yaml.parser.ParserError as err: log.error(err) return {} ret = {} for source in sources: if (not isinstance(source, dict)) or len(source) != 1: log.error('Invalid input: %s', pprint.pformat(sources)) log.error('Input must be a list of 1-element dicts') return {} else: key = next(iter(source)) ret[_normalize_name(key)] = source[key] return ret def parse_targets(name=None, pkgs=None, sources=None, saltenv='base', normalize=True, **kwargs): ''' Parses the input to pkg.install and returns back the package(s) to be installed. Returns a list of packages, as well as a string noting whether the packages are to come from a repository or a binary package. CLI Example: .. code-block:: bash salt '*' pkg_resource.parse_targets ''' if '__env__' in kwargs: # "env" is not supported; Use "saltenv". kwargs.pop('__env__') if __grains__['os'] == 'MacOS' and sources: log.warning('Parameter "sources" ignored on MacOS hosts.') version = kwargs.get('version') if pkgs and sources: log.error('Only one of "pkgs" and "sources" can be used.') return None, None elif 'advisory_ids' in kwargs: if pkgs: log.error('Cannot use "advisory_ids" and "pkgs" at the same time') return None, None elif kwargs['advisory_ids']: return kwargs['advisory_ids'], 'advisory' else: return [name], 'advisory' elif pkgs: if version is not None: log.warning('\'version\' argument will be ignored for multiple ' 'package targets') pkgs = _repack_pkgs(pkgs, normalize=normalize) if not pkgs: return None, None else: return pkgs, 'repository' elif sources and __grains__['os'] != 'MacOS': if version is not None: log.warning('\'version\' argument will be ignored for multiple ' 'package targets') sources = pack_sources(sources, normalize=normalize) if not sources: return None, None srcinfo = [] for pkg_name, pkg_src in six.iteritems(sources): if __salt__['config.valid_fileproto'](pkg_src): # Cache package from remote source (salt master, HTTP, FTP) and # append the cached path. srcinfo.append(__salt__['cp.cache_file'](pkg_src, saltenv)) else: # Package file local to the minion, just append the path to the # package file. if not os.path.isabs(pkg_src): raise SaltInvocationError( 'Path {0} for package {1} is either not absolute or ' 'an invalid protocol'.format(pkg_src, pkg_name) ) srcinfo.append(pkg_src) return srcinfo, 'file' elif name: if normalize: _normalize_name = \ __salt__.get('pkg.normalize_name', lambda pkgname: pkgname) packed = dict([(_normalize_name(x), version) for x in name.split(',')]) else: packed = dict([(x, version) for x in name.split(',')]) return packed, 'repository' else: log.error('No package sources provided') return None, None def version(*names, **kwargs): ''' Common interface for obtaining the version of installed packages. CLI Example: .. code-block:: bash salt '*' pkg_resource.version vim salt '*' pkg_resource.version foo bar baz salt '*' pkg_resource.version 'python*' ''' ret = {} versions_as_list = \ salt.utils.data.is_true(kwargs.pop('versions_as_list', False)) pkg_glob = False if names: pkgs = __salt__['pkg.list_pkgs'](versions_as_list=True, **kwargs) for name in names: if '*' in name: pkg_glob = True for match in fnmatch.filter(pkgs, name): ret[match] = pkgs.get(match, []) else: ret[name] = pkgs.get(name, []) if not versions_as_list: __salt__['pkg_resource.stringify'](ret) # Return a string if no globbing is used, and there is one item in the # return dict if len(ret) == 1 and not pkg_glob: try: return next(six.itervalues(ret)) except StopIteration: return '' return ret def add_pkg(pkgs, name, pkgver): ''' Add a package to a dict of installed packages. CLI Example: .. code-block:: bash salt '*' pkg_resource.add_pkg '{}' bind 9 ''' try: pkgs.setdefault(name, []).append(pkgver) except AttributeError as exc: log.exception(exc) def stringify(pkgs): ''' Takes a dict of package name/version information and joins each list of installed versions into a string. CLI Example: .. code-block:: bash salt '*' pkg_resource.stringify 'vim: 7.127' ''' try: for key in pkgs: pkgs[key] = ','.join(pkgs[key]) except AttributeError as exc: log.exception(exc) def version_clean(verstr): ''' Clean the version string removing extra data. This function will simply try to call ``pkg.version_clean``. CLI Example: .. code-block:: bash salt '*' pkg_resource.version_clean <version_string> ''' if verstr and 'pkg.version_clean' in __salt__: return __salt__['pkg.version_clean'](verstr) return verstr def check_extra_requirements(pkgname, pkgver): ''' Check if the installed package already has the given requirements. This function will return the result of ``pkg.check_extra_requirements`` if this function exists for the minion, otherwise it will return True. CLI Example: .. code-block:: bash salt '*' pkg_resource.check_extra_requirements <pkgname> <extra_requirements> ''' if pkgver and 'pkg.check_extra_requirements' in __salt__: return __salt__['pkg.check_extra_requirements'](pkgname, pkgver) return True def format_pkg_list(packages, versions_as_list, attr): ''' Formats packages according to parameters for list_pkgs. ''' ret = copy.deepcopy(packages) if attr: requested_attr = {'epoch', 'version', 'release', 'arch', 'install_date', 'install_date_time_t'} if attr != 'all': requested_attr &= set(attr + ['version']) for name in ret: versions = [] for all_attr in ret[name]: filtered_attr = {} for key in requested_attr: if all_attr[key]: filtered_attr[key] = all_attr[key] versions.append(filtered_attr) ret[name] = versions return ret for name in ret: ret[name] = [format_version(d['epoch'], d['version'], d['release']) for d in ret[name]] if not versions_as_list: stringify(ret) return ret def format_version(epoch, version, release): ''' Formats a version string for list_pkgs. ''' full_version = '{0}:{1}'.format(epoch, version) if epoch else version if release: full_version += '-{0}'.format(release) return full_version
saltstack/salt
salt/modules/pkg_resource.py
stringify
python
def stringify(pkgs): ''' Takes a dict of package name/version information and joins each list of installed versions into a string. CLI Example: .. code-block:: bash salt '*' pkg_resource.stringify 'vim: 7.127' ''' try: for key in pkgs: pkgs[key] = ','.join(pkgs[key]) except AttributeError as exc: log.exception(exc)
Takes a dict of package name/version information and joins each list of installed versions into a string. CLI Example: .. code-block:: bash salt '*' pkg_resource.stringify 'vim: 7.127'
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/pkg_resource.py#L256-L271
null
# -*- coding: utf-8 -*- ''' Resources needed by pkg providers ''' # Import python libs from __future__ import absolute_import, print_function, unicode_literals import copy import fnmatch import logging import os import pprint # Import third party libs from salt.ext import six # Import salt libs import salt.utils.data import salt.utils.versions import salt.utils.yaml from salt.exceptions import SaltInvocationError log = logging.getLogger(__name__) __SUFFIX_NOT_NEEDED = ('x86_64', 'noarch') def _repack_pkgs(pkgs, normalize=True): ''' Repack packages specified using "pkgs" argument to pkg states into a single dictionary ''' if normalize and 'pkg.normalize_name' in __salt__: _normalize_name = __salt__['pkg.normalize_name'] else: _normalize_name = lambda pkgname: pkgname return dict( [ (_normalize_name(six.text_type(x)), six.text_type(y) if y is not None else y) for x, y in six.iteritems(salt.utils.data.repack_dictlist(pkgs)) ] ) def pack_sources(sources, normalize=True): ''' Accepts list of dicts (or a string representing a list of dicts) and packs the key/value pairs into a single dict. ``'[{"foo": "salt://foo.rpm"}, {"bar": "salt://bar.rpm"}]'`` would become ``{"foo": "salt://foo.rpm", "bar": "salt://bar.rpm"}`` normalize : True Normalize the package name by removing the architecture, if the architecture of the package is different from the architecture of the operating system. The ability to disable this behavior is useful for poorly-created packages which include the architecture as an actual part of the name, such as kernel modules which match a specific kernel version. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt '*' pkg_resource.pack_sources '[{"foo": "salt://foo.rpm"}, {"bar": "salt://bar.rpm"}]' ''' if normalize and 'pkg.normalize_name' in __salt__: _normalize_name = __salt__['pkg.normalize_name'] else: _normalize_name = lambda pkgname: pkgname if isinstance(sources, six.string_types): try: sources = salt.utils.yaml.safe_load(sources) except salt.utils.yaml.parser.ParserError as err: log.error(err) return {} ret = {} for source in sources: if (not isinstance(source, dict)) or len(source) != 1: log.error('Invalid input: %s', pprint.pformat(sources)) log.error('Input must be a list of 1-element dicts') return {} else: key = next(iter(source)) ret[_normalize_name(key)] = source[key] return ret def parse_targets(name=None, pkgs=None, sources=None, saltenv='base', normalize=True, **kwargs): ''' Parses the input to pkg.install and returns back the package(s) to be installed. Returns a list of packages, as well as a string noting whether the packages are to come from a repository or a binary package. CLI Example: .. code-block:: bash salt '*' pkg_resource.parse_targets ''' if '__env__' in kwargs: # "env" is not supported; Use "saltenv". kwargs.pop('__env__') if __grains__['os'] == 'MacOS' and sources: log.warning('Parameter "sources" ignored on MacOS hosts.') version = kwargs.get('version') if pkgs and sources: log.error('Only one of "pkgs" and "sources" can be used.') return None, None elif 'advisory_ids' in kwargs: if pkgs: log.error('Cannot use "advisory_ids" and "pkgs" at the same time') return None, None elif kwargs['advisory_ids']: return kwargs['advisory_ids'], 'advisory' else: return [name], 'advisory' elif pkgs: if version is not None: log.warning('\'version\' argument will be ignored for multiple ' 'package targets') pkgs = _repack_pkgs(pkgs, normalize=normalize) if not pkgs: return None, None else: return pkgs, 'repository' elif sources and __grains__['os'] != 'MacOS': if version is not None: log.warning('\'version\' argument will be ignored for multiple ' 'package targets') sources = pack_sources(sources, normalize=normalize) if not sources: return None, None srcinfo = [] for pkg_name, pkg_src in six.iteritems(sources): if __salt__['config.valid_fileproto'](pkg_src): # Cache package from remote source (salt master, HTTP, FTP) and # append the cached path. srcinfo.append(__salt__['cp.cache_file'](pkg_src, saltenv)) else: # Package file local to the minion, just append the path to the # package file. if not os.path.isabs(pkg_src): raise SaltInvocationError( 'Path {0} for package {1} is either not absolute or ' 'an invalid protocol'.format(pkg_src, pkg_name) ) srcinfo.append(pkg_src) return srcinfo, 'file' elif name: if normalize: _normalize_name = \ __salt__.get('pkg.normalize_name', lambda pkgname: pkgname) packed = dict([(_normalize_name(x), version) for x in name.split(',')]) else: packed = dict([(x, version) for x in name.split(',')]) return packed, 'repository' else: log.error('No package sources provided') return None, None def version(*names, **kwargs): ''' Common interface for obtaining the version of installed packages. CLI Example: .. code-block:: bash salt '*' pkg_resource.version vim salt '*' pkg_resource.version foo bar baz salt '*' pkg_resource.version 'python*' ''' ret = {} versions_as_list = \ salt.utils.data.is_true(kwargs.pop('versions_as_list', False)) pkg_glob = False if names: pkgs = __salt__['pkg.list_pkgs'](versions_as_list=True, **kwargs) for name in names: if '*' in name: pkg_glob = True for match in fnmatch.filter(pkgs, name): ret[match] = pkgs.get(match, []) else: ret[name] = pkgs.get(name, []) if not versions_as_list: __salt__['pkg_resource.stringify'](ret) # Return a string if no globbing is used, and there is one item in the # return dict if len(ret) == 1 and not pkg_glob: try: return next(six.itervalues(ret)) except StopIteration: return '' return ret def add_pkg(pkgs, name, pkgver): ''' Add a package to a dict of installed packages. CLI Example: .. code-block:: bash salt '*' pkg_resource.add_pkg '{}' bind 9 ''' try: pkgs.setdefault(name, []).append(pkgver) except AttributeError as exc: log.exception(exc) def sort_pkglist(pkgs): ''' Accepts a dict obtained from pkg.list_pkgs() and sorts in place the list of versions for any packages that have multiple versions installed, so that two package lists can be compared to one another. CLI Example: .. code-block:: bash salt '*' pkg_resource.sort_pkglist '["3.45", "2.13"]' ''' # It doesn't matter that ['4.9','4.10'] would be sorted to ['4.10','4.9'], # so long as the sorting is consistent. try: for key in pkgs: # Passing the pkglist to set() also removes duplicate version # numbers (if present). pkgs[key] = sorted(set(pkgs[key])) except AttributeError as exc: log.exception(exc) def version_clean(verstr): ''' Clean the version string removing extra data. This function will simply try to call ``pkg.version_clean``. CLI Example: .. code-block:: bash salt '*' pkg_resource.version_clean <version_string> ''' if verstr and 'pkg.version_clean' in __salt__: return __salt__['pkg.version_clean'](verstr) return verstr def check_extra_requirements(pkgname, pkgver): ''' Check if the installed package already has the given requirements. This function will return the result of ``pkg.check_extra_requirements`` if this function exists for the minion, otherwise it will return True. CLI Example: .. code-block:: bash salt '*' pkg_resource.check_extra_requirements <pkgname> <extra_requirements> ''' if pkgver and 'pkg.check_extra_requirements' in __salt__: return __salt__['pkg.check_extra_requirements'](pkgname, pkgver) return True def format_pkg_list(packages, versions_as_list, attr): ''' Formats packages according to parameters for list_pkgs. ''' ret = copy.deepcopy(packages) if attr: requested_attr = {'epoch', 'version', 'release', 'arch', 'install_date', 'install_date_time_t'} if attr != 'all': requested_attr &= set(attr + ['version']) for name in ret: versions = [] for all_attr in ret[name]: filtered_attr = {} for key in requested_attr: if all_attr[key]: filtered_attr[key] = all_attr[key] versions.append(filtered_attr) ret[name] = versions return ret for name in ret: ret[name] = [format_version(d['epoch'], d['version'], d['release']) for d in ret[name]] if not versions_as_list: stringify(ret) return ret def format_version(epoch, version, release): ''' Formats a version string for list_pkgs. ''' full_version = '{0}:{1}'.format(epoch, version) if epoch else version if release: full_version += '-{0}'.format(release) return full_version
saltstack/salt
salt/modules/pkg_resource.py
format_pkg_list
python
def format_pkg_list(packages, versions_as_list, attr): ''' Formats packages according to parameters for list_pkgs. ''' ret = copy.deepcopy(packages) if attr: requested_attr = {'epoch', 'version', 'release', 'arch', 'install_date', 'install_date_time_t'} if attr != 'all': requested_attr &= set(attr + ['version']) for name in ret: versions = [] for all_attr in ret[name]: filtered_attr = {} for key in requested_attr: if all_attr[key]: filtered_attr[key] = all_attr[key] versions.append(filtered_attr) ret[name] = versions return ret for name in ret: ret[name] = [format_version(d['epoch'], d['version'], d['release']) for d in ret[name]] if not versions_as_list: stringify(ret) return ret
Formats packages according to parameters for list_pkgs.
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/pkg_resource.py#L308-L335
[ "def stringify(pkgs):\n '''\n Takes a dict of package name/version information and joins each list of\n installed versions into a string.\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' pkg_resource.stringify 'vim: 7.127'\n '''\n try:\n for key in pkgs:\n pkgs[key] = ','.join(pkgs[key])\n except AttributeError as exc:\n log.exception(exc)\n" ]
# -*- coding: utf-8 -*- ''' Resources needed by pkg providers ''' # Import python libs from __future__ import absolute_import, print_function, unicode_literals import copy import fnmatch import logging import os import pprint # Import third party libs from salt.ext import six # Import salt libs import salt.utils.data import salt.utils.versions import salt.utils.yaml from salt.exceptions import SaltInvocationError log = logging.getLogger(__name__) __SUFFIX_NOT_NEEDED = ('x86_64', 'noarch') def _repack_pkgs(pkgs, normalize=True): ''' Repack packages specified using "pkgs" argument to pkg states into a single dictionary ''' if normalize and 'pkg.normalize_name' in __salt__: _normalize_name = __salt__['pkg.normalize_name'] else: _normalize_name = lambda pkgname: pkgname return dict( [ (_normalize_name(six.text_type(x)), six.text_type(y) if y is not None else y) for x, y in six.iteritems(salt.utils.data.repack_dictlist(pkgs)) ] ) def pack_sources(sources, normalize=True): ''' Accepts list of dicts (or a string representing a list of dicts) and packs the key/value pairs into a single dict. ``'[{"foo": "salt://foo.rpm"}, {"bar": "salt://bar.rpm"}]'`` would become ``{"foo": "salt://foo.rpm", "bar": "salt://bar.rpm"}`` normalize : True Normalize the package name by removing the architecture, if the architecture of the package is different from the architecture of the operating system. The ability to disable this behavior is useful for poorly-created packages which include the architecture as an actual part of the name, such as kernel modules which match a specific kernel version. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt '*' pkg_resource.pack_sources '[{"foo": "salt://foo.rpm"}, {"bar": "salt://bar.rpm"}]' ''' if normalize and 'pkg.normalize_name' in __salt__: _normalize_name = __salt__['pkg.normalize_name'] else: _normalize_name = lambda pkgname: pkgname if isinstance(sources, six.string_types): try: sources = salt.utils.yaml.safe_load(sources) except salt.utils.yaml.parser.ParserError as err: log.error(err) return {} ret = {} for source in sources: if (not isinstance(source, dict)) or len(source) != 1: log.error('Invalid input: %s', pprint.pformat(sources)) log.error('Input must be a list of 1-element dicts') return {} else: key = next(iter(source)) ret[_normalize_name(key)] = source[key] return ret def parse_targets(name=None, pkgs=None, sources=None, saltenv='base', normalize=True, **kwargs): ''' Parses the input to pkg.install and returns back the package(s) to be installed. Returns a list of packages, as well as a string noting whether the packages are to come from a repository or a binary package. CLI Example: .. code-block:: bash salt '*' pkg_resource.parse_targets ''' if '__env__' in kwargs: # "env" is not supported; Use "saltenv". kwargs.pop('__env__') if __grains__['os'] == 'MacOS' and sources: log.warning('Parameter "sources" ignored on MacOS hosts.') version = kwargs.get('version') if pkgs and sources: log.error('Only one of "pkgs" and "sources" can be used.') return None, None elif 'advisory_ids' in kwargs: if pkgs: log.error('Cannot use "advisory_ids" and "pkgs" at the same time') return None, None elif kwargs['advisory_ids']: return kwargs['advisory_ids'], 'advisory' else: return [name], 'advisory' elif pkgs: if version is not None: log.warning('\'version\' argument will be ignored for multiple ' 'package targets') pkgs = _repack_pkgs(pkgs, normalize=normalize) if not pkgs: return None, None else: return pkgs, 'repository' elif sources and __grains__['os'] != 'MacOS': if version is not None: log.warning('\'version\' argument will be ignored for multiple ' 'package targets') sources = pack_sources(sources, normalize=normalize) if not sources: return None, None srcinfo = [] for pkg_name, pkg_src in six.iteritems(sources): if __salt__['config.valid_fileproto'](pkg_src): # Cache package from remote source (salt master, HTTP, FTP) and # append the cached path. srcinfo.append(__salt__['cp.cache_file'](pkg_src, saltenv)) else: # Package file local to the minion, just append the path to the # package file. if not os.path.isabs(pkg_src): raise SaltInvocationError( 'Path {0} for package {1} is either not absolute or ' 'an invalid protocol'.format(pkg_src, pkg_name) ) srcinfo.append(pkg_src) return srcinfo, 'file' elif name: if normalize: _normalize_name = \ __salt__.get('pkg.normalize_name', lambda pkgname: pkgname) packed = dict([(_normalize_name(x), version) for x in name.split(',')]) else: packed = dict([(x, version) for x in name.split(',')]) return packed, 'repository' else: log.error('No package sources provided') return None, None def version(*names, **kwargs): ''' Common interface for obtaining the version of installed packages. CLI Example: .. code-block:: bash salt '*' pkg_resource.version vim salt '*' pkg_resource.version foo bar baz salt '*' pkg_resource.version 'python*' ''' ret = {} versions_as_list = \ salt.utils.data.is_true(kwargs.pop('versions_as_list', False)) pkg_glob = False if names: pkgs = __salt__['pkg.list_pkgs'](versions_as_list=True, **kwargs) for name in names: if '*' in name: pkg_glob = True for match in fnmatch.filter(pkgs, name): ret[match] = pkgs.get(match, []) else: ret[name] = pkgs.get(name, []) if not versions_as_list: __salt__['pkg_resource.stringify'](ret) # Return a string if no globbing is used, and there is one item in the # return dict if len(ret) == 1 and not pkg_glob: try: return next(six.itervalues(ret)) except StopIteration: return '' return ret def add_pkg(pkgs, name, pkgver): ''' Add a package to a dict of installed packages. CLI Example: .. code-block:: bash salt '*' pkg_resource.add_pkg '{}' bind 9 ''' try: pkgs.setdefault(name, []).append(pkgver) except AttributeError as exc: log.exception(exc) def sort_pkglist(pkgs): ''' Accepts a dict obtained from pkg.list_pkgs() and sorts in place the list of versions for any packages that have multiple versions installed, so that two package lists can be compared to one another. CLI Example: .. code-block:: bash salt '*' pkg_resource.sort_pkglist '["3.45", "2.13"]' ''' # It doesn't matter that ['4.9','4.10'] would be sorted to ['4.10','4.9'], # so long as the sorting is consistent. try: for key in pkgs: # Passing the pkglist to set() also removes duplicate version # numbers (if present). pkgs[key] = sorted(set(pkgs[key])) except AttributeError as exc: log.exception(exc) def stringify(pkgs): ''' Takes a dict of package name/version information and joins each list of installed versions into a string. CLI Example: .. code-block:: bash salt '*' pkg_resource.stringify 'vim: 7.127' ''' try: for key in pkgs: pkgs[key] = ','.join(pkgs[key]) except AttributeError as exc: log.exception(exc) def version_clean(verstr): ''' Clean the version string removing extra data. This function will simply try to call ``pkg.version_clean``. CLI Example: .. code-block:: bash salt '*' pkg_resource.version_clean <version_string> ''' if verstr and 'pkg.version_clean' in __salt__: return __salt__['pkg.version_clean'](verstr) return verstr def check_extra_requirements(pkgname, pkgver): ''' Check if the installed package already has the given requirements. This function will return the result of ``pkg.check_extra_requirements`` if this function exists for the minion, otherwise it will return True. CLI Example: .. code-block:: bash salt '*' pkg_resource.check_extra_requirements <pkgname> <extra_requirements> ''' if pkgver and 'pkg.check_extra_requirements' in __salt__: return __salt__['pkg.check_extra_requirements'](pkgname, pkgver) return True def format_version(epoch, version, release): ''' Formats a version string for list_pkgs. ''' full_version = '{0}:{1}'.format(epoch, version) if epoch else version if release: full_version += '-{0}'.format(release) return full_version
saltstack/salt
salt/modules/pkg_resource.py
format_version
python
def format_version(epoch, version, release): ''' Formats a version string for list_pkgs. ''' full_version = '{0}:{1}'.format(epoch, version) if epoch else version if release: full_version += '-{0}'.format(release) return full_version
Formats a version string for list_pkgs.
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/pkg_resource.py#L338-L345
null
# -*- coding: utf-8 -*- ''' Resources needed by pkg providers ''' # Import python libs from __future__ import absolute_import, print_function, unicode_literals import copy import fnmatch import logging import os import pprint # Import third party libs from salt.ext import six # Import salt libs import salt.utils.data import salt.utils.versions import salt.utils.yaml from salt.exceptions import SaltInvocationError log = logging.getLogger(__name__) __SUFFIX_NOT_NEEDED = ('x86_64', 'noarch') def _repack_pkgs(pkgs, normalize=True): ''' Repack packages specified using "pkgs" argument to pkg states into a single dictionary ''' if normalize and 'pkg.normalize_name' in __salt__: _normalize_name = __salt__['pkg.normalize_name'] else: _normalize_name = lambda pkgname: pkgname return dict( [ (_normalize_name(six.text_type(x)), six.text_type(y) if y is not None else y) for x, y in six.iteritems(salt.utils.data.repack_dictlist(pkgs)) ] ) def pack_sources(sources, normalize=True): ''' Accepts list of dicts (or a string representing a list of dicts) and packs the key/value pairs into a single dict. ``'[{"foo": "salt://foo.rpm"}, {"bar": "salt://bar.rpm"}]'`` would become ``{"foo": "salt://foo.rpm", "bar": "salt://bar.rpm"}`` normalize : True Normalize the package name by removing the architecture, if the architecture of the package is different from the architecture of the operating system. The ability to disable this behavior is useful for poorly-created packages which include the architecture as an actual part of the name, such as kernel modules which match a specific kernel version. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt '*' pkg_resource.pack_sources '[{"foo": "salt://foo.rpm"}, {"bar": "salt://bar.rpm"}]' ''' if normalize and 'pkg.normalize_name' in __salt__: _normalize_name = __salt__['pkg.normalize_name'] else: _normalize_name = lambda pkgname: pkgname if isinstance(sources, six.string_types): try: sources = salt.utils.yaml.safe_load(sources) except salt.utils.yaml.parser.ParserError as err: log.error(err) return {} ret = {} for source in sources: if (not isinstance(source, dict)) or len(source) != 1: log.error('Invalid input: %s', pprint.pformat(sources)) log.error('Input must be a list of 1-element dicts') return {} else: key = next(iter(source)) ret[_normalize_name(key)] = source[key] return ret def parse_targets(name=None, pkgs=None, sources=None, saltenv='base', normalize=True, **kwargs): ''' Parses the input to pkg.install and returns back the package(s) to be installed. Returns a list of packages, as well as a string noting whether the packages are to come from a repository or a binary package. CLI Example: .. code-block:: bash salt '*' pkg_resource.parse_targets ''' if '__env__' in kwargs: # "env" is not supported; Use "saltenv". kwargs.pop('__env__') if __grains__['os'] == 'MacOS' and sources: log.warning('Parameter "sources" ignored on MacOS hosts.') version = kwargs.get('version') if pkgs and sources: log.error('Only one of "pkgs" and "sources" can be used.') return None, None elif 'advisory_ids' in kwargs: if pkgs: log.error('Cannot use "advisory_ids" and "pkgs" at the same time') return None, None elif kwargs['advisory_ids']: return kwargs['advisory_ids'], 'advisory' else: return [name], 'advisory' elif pkgs: if version is not None: log.warning('\'version\' argument will be ignored for multiple ' 'package targets') pkgs = _repack_pkgs(pkgs, normalize=normalize) if not pkgs: return None, None else: return pkgs, 'repository' elif sources and __grains__['os'] != 'MacOS': if version is not None: log.warning('\'version\' argument will be ignored for multiple ' 'package targets') sources = pack_sources(sources, normalize=normalize) if not sources: return None, None srcinfo = [] for pkg_name, pkg_src in six.iteritems(sources): if __salt__['config.valid_fileproto'](pkg_src): # Cache package from remote source (salt master, HTTP, FTP) and # append the cached path. srcinfo.append(__salt__['cp.cache_file'](pkg_src, saltenv)) else: # Package file local to the minion, just append the path to the # package file. if not os.path.isabs(pkg_src): raise SaltInvocationError( 'Path {0} for package {1} is either not absolute or ' 'an invalid protocol'.format(pkg_src, pkg_name) ) srcinfo.append(pkg_src) return srcinfo, 'file' elif name: if normalize: _normalize_name = \ __salt__.get('pkg.normalize_name', lambda pkgname: pkgname) packed = dict([(_normalize_name(x), version) for x in name.split(',')]) else: packed = dict([(x, version) for x in name.split(',')]) return packed, 'repository' else: log.error('No package sources provided') return None, None def version(*names, **kwargs): ''' Common interface for obtaining the version of installed packages. CLI Example: .. code-block:: bash salt '*' pkg_resource.version vim salt '*' pkg_resource.version foo bar baz salt '*' pkg_resource.version 'python*' ''' ret = {} versions_as_list = \ salt.utils.data.is_true(kwargs.pop('versions_as_list', False)) pkg_glob = False if names: pkgs = __salt__['pkg.list_pkgs'](versions_as_list=True, **kwargs) for name in names: if '*' in name: pkg_glob = True for match in fnmatch.filter(pkgs, name): ret[match] = pkgs.get(match, []) else: ret[name] = pkgs.get(name, []) if not versions_as_list: __salt__['pkg_resource.stringify'](ret) # Return a string if no globbing is used, and there is one item in the # return dict if len(ret) == 1 and not pkg_glob: try: return next(six.itervalues(ret)) except StopIteration: return '' return ret def add_pkg(pkgs, name, pkgver): ''' Add a package to a dict of installed packages. CLI Example: .. code-block:: bash salt '*' pkg_resource.add_pkg '{}' bind 9 ''' try: pkgs.setdefault(name, []).append(pkgver) except AttributeError as exc: log.exception(exc) def sort_pkglist(pkgs): ''' Accepts a dict obtained from pkg.list_pkgs() and sorts in place the list of versions for any packages that have multiple versions installed, so that two package lists can be compared to one another. CLI Example: .. code-block:: bash salt '*' pkg_resource.sort_pkglist '["3.45", "2.13"]' ''' # It doesn't matter that ['4.9','4.10'] would be sorted to ['4.10','4.9'], # so long as the sorting is consistent. try: for key in pkgs: # Passing the pkglist to set() also removes duplicate version # numbers (if present). pkgs[key] = sorted(set(pkgs[key])) except AttributeError as exc: log.exception(exc) def stringify(pkgs): ''' Takes a dict of package name/version information and joins each list of installed versions into a string. CLI Example: .. code-block:: bash salt '*' pkg_resource.stringify 'vim: 7.127' ''' try: for key in pkgs: pkgs[key] = ','.join(pkgs[key]) except AttributeError as exc: log.exception(exc) def version_clean(verstr): ''' Clean the version string removing extra data. This function will simply try to call ``pkg.version_clean``. CLI Example: .. code-block:: bash salt '*' pkg_resource.version_clean <version_string> ''' if verstr and 'pkg.version_clean' in __salt__: return __salt__['pkg.version_clean'](verstr) return verstr def check_extra_requirements(pkgname, pkgver): ''' Check if the installed package already has the given requirements. This function will return the result of ``pkg.check_extra_requirements`` if this function exists for the minion, otherwise it will return True. CLI Example: .. code-block:: bash salt '*' pkg_resource.check_extra_requirements <pkgname> <extra_requirements> ''' if pkgver and 'pkg.check_extra_requirements' in __salt__: return __salt__['pkg.check_extra_requirements'](pkgname, pkgver) return True def format_pkg_list(packages, versions_as_list, attr): ''' Formats packages according to parameters for list_pkgs. ''' ret = copy.deepcopy(packages) if attr: requested_attr = {'epoch', 'version', 'release', 'arch', 'install_date', 'install_date_time_t'} if attr != 'all': requested_attr &= set(attr + ['version']) for name in ret: versions = [] for all_attr in ret[name]: filtered_attr = {} for key in requested_attr: if all_attr[key]: filtered_attr[key] = all_attr[key] versions.append(filtered_attr) ret[name] = versions return ret for name in ret: ret[name] = [format_version(d['epoch'], d['version'], d['release']) for d in ret[name]] if not versions_as_list: stringify(ret) return ret
saltstack/salt
salt/states/makeconf.py
_make_set
python
def _make_set(var): ''' Force var to be a set ''' if var is None: return set() if not isinstance(var, list): if isinstance(var, six.string_types): var = var.split() else: var = list(var) return set(var)
Force var to be a set
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/makeconf.py#L27-L38
null
# -*- coding: utf-8 -*- ''' Management of Gentoo make.conf ============================== A state module to manage Gentoo's ``make.conf`` file .. code-block:: yaml makeopts: makeconf.present: - value: '-j3' ''' from __future__ import absolute_import, print_function, unicode_literals # Import 3rd-party libs from salt.ext import six def __virtual__(): ''' Only load if the makeconf module is available in __salt__ ''' return 'makeconf' if 'makeconf.get_var' in __salt__ else False def present(name, value=None, contains=None, excludes=None): ''' Verify that the variable is in the ``make.conf`` and has the provided settings. If value is set, contains and excludes will be ignored. name The variable name. This will automatically be converted to upper case since variables in ``make.conf`` are in upper case value Enforce that the value of the variable is set to the provided value contains Enforce that the value of the variable contains the provided value excludes Enforce that the value of the variable does not contain the provided value. ''' ret = {'changes': {}, 'comment': '', 'name': name, 'result': True} # Make name all Uppers since make.conf uses all Upper vars upper_name = name.upper() old_value = __salt__['makeconf.get_var'](upper_name) # If only checking if variable is present allows for setting the # variable outside of salt states, but the state can still ensure # that is exists if value is None and contains is None and excludes is None: # variable is present if old_value is not None: msg = 'Variable {0} is already present in make.conf' ret['comment'] = msg.format(name) else: if __opts__['test']: msg = 'Variable {0} is to be set in make.conf' ret['comment'] = msg.format(name) ret['result'] = None else: changes = __salt__['makeconf.set_var'](upper_name, '') # If failed to be set if changes[upper_name]['new'] is None: msg = 'Variable {0} failed to be set in make.conf' ret['comment'] = msg.format(name) ret['result'] = False else: msg = 'Variable {0} set in make.conf' ret['comment'] = msg.format(name) elif value is not None: # variable is present and is set to value if old_value is not None and old_value == value: msg = 'Variable {0} is already "{1}" in make.conf' ret['comment'] = msg.format(name, value) else: if __opts__['test']: msg = 'Variable {0} is to be set to "{1}" in make.conf' ret['comment'] = msg.format(name, value) ret['result'] = None else: changes = __salt__['makeconf.set_var'](upper_name, value) # If failed to be set new_value = __salt__['makeconf.get_var'](upper_name) if new_value is None or new_value != value: msg = 'Variable {0} failed to be set in make.conf' ret['comment'] = msg.format(name) ret['result'] = False else: msg = 'Variable {0} is set in make.conf' ret['changes'] = changes ret['comment'] = msg.format(name) elif contains is not None or excludes is not None: # Make these into sets to easily compare things contains_set = _make_set(contains) excludes_set = _make_set(excludes) old_value_set = _make_set(old_value) if contains_set.intersection(excludes_set): msg = 'Variable {0} cannot contain and exclude the same value' ret['comment'] = msg.format(name) ret['result'] = False else: to_append = set() to_trim = set() if contains is not None: to_append = contains_set.difference(old_value_set) if excludes is not None: to_trim = excludes_set.intersection(old_value_set) if not to_append and not to_trim: msg = 'Variable {0} is correct in make.conf' ret['comment'] = msg.format(name) else: if __opts__['test']: msg = 'Variable {0} is set to'.format(name) if to_append: msg += ' append "{0}"'.format(list(to_append)) if to_trim: msg += ' trim "{0}"'.format(list(to_trim)) msg += ' in make.conf' ret['comment'] = msg ret['result'] = None else: for value in to_append: __salt__['makeconf.append_var'](upper_name, value) for value in to_trim: __salt__['makeconf.trim_var'](upper_name, value) new_value = __salt__['makeconf.get_var'](upper_name) # TODO verify appends and trims worked ret['changes'] = {upper_name: {'old': old_value, 'new': new_value}} msg = 'Variable {0} is correct in make.conf' ret['comment'] = msg.format(name) # Now finally return return ret def absent(name): ''' Verify that the variable is not in the ``make.conf``. name The variable name. This will automatically be converted to upper case since variables in ``make.conf`` are in upper case ''' ret = {'changes': {}, 'comment': '', 'name': name, 'result': True} # Make name all Uppers since make.conf uses all Upper vars upper_name = name.upper() old_value = __salt__['makeconf.get_var'](upper_name) if old_value is None: msg = 'Variable {0} is already absent from make.conf' ret['comment'] = msg.format(name) else: if __opts__['test']: msg = 'Variable {0} is set to be removed from make.conf' ret['comment'] = msg.format(name) ret['result'] = None else: __salt__['makeconf.remove_var'](upper_name) new_value = __salt__['makeconf.get_var'](upper_name) if new_value is not None: msg = 'Variable {0} failed to be removed from make.conf' ret['comment'] = msg.format(name) ret['result'] = False else: msg = 'Variable {0} was removed from make.conf' ret['comment'] = msg.format(name) ret['result'] = True return ret
saltstack/salt
salt/states/makeconf.py
present
python
def present(name, value=None, contains=None, excludes=None): ''' Verify that the variable is in the ``make.conf`` and has the provided settings. If value is set, contains and excludes will be ignored. name The variable name. This will automatically be converted to upper case since variables in ``make.conf`` are in upper case value Enforce that the value of the variable is set to the provided value contains Enforce that the value of the variable contains the provided value excludes Enforce that the value of the variable does not contain the provided value. ''' ret = {'changes': {}, 'comment': '', 'name': name, 'result': True} # Make name all Uppers since make.conf uses all Upper vars upper_name = name.upper() old_value = __salt__['makeconf.get_var'](upper_name) # If only checking if variable is present allows for setting the # variable outside of salt states, but the state can still ensure # that is exists if value is None and contains is None and excludes is None: # variable is present if old_value is not None: msg = 'Variable {0} is already present in make.conf' ret['comment'] = msg.format(name) else: if __opts__['test']: msg = 'Variable {0} is to be set in make.conf' ret['comment'] = msg.format(name) ret['result'] = None else: changes = __salt__['makeconf.set_var'](upper_name, '') # If failed to be set if changes[upper_name]['new'] is None: msg = 'Variable {0} failed to be set in make.conf' ret['comment'] = msg.format(name) ret['result'] = False else: msg = 'Variable {0} set in make.conf' ret['comment'] = msg.format(name) elif value is not None: # variable is present and is set to value if old_value is not None and old_value == value: msg = 'Variable {0} is already "{1}" in make.conf' ret['comment'] = msg.format(name, value) else: if __opts__['test']: msg = 'Variable {0} is to be set to "{1}" in make.conf' ret['comment'] = msg.format(name, value) ret['result'] = None else: changes = __salt__['makeconf.set_var'](upper_name, value) # If failed to be set new_value = __salt__['makeconf.get_var'](upper_name) if new_value is None or new_value != value: msg = 'Variable {0} failed to be set in make.conf' ret['comment'] = msg.format(name) ret['result'] = False else: msg = 'Variable {0} is set in make.conf' ret['changes'] = changes ret['comment'] = msg.format(name) elif contains is not None or excludes is not None: # Make these into sets to easily compare things contains_set = _make_set(contains) excludes_set = _make_set(excludes) old_value_set = _make_set(old_value) if contains_set.intersection(excludes_set): msg = 'Variable {0} cannot contain and exclude the same value' ret['comment'] = msg.format(name) ret['result'] = False else: to_append = set() to_trim = set() if contains is not None: to_append = contains_set.difference(old_value_set) if excludes is not None: to_trim = excludes_set.intersection(old_value_set) if not to_append and not to_trim: msg = 'Variable {0} is correct in make.conf' ret['comment'] = msg.format(name) else: if __opts__['test']: msg = 'Variable {0} is set to'.format(name) if to_append: msg += ' append "{0}"'.format(list(to_append)) if to_trim: msg += ' trim "{0}"'.format(list(to_trim)) msg += ' in make.conf' ret['comment'] = msg ret['result'] = None else: for value in to_append: __salt__['makeconf.append_var'](upper_name, value) for value in to_trim: __salt__['makeconf.trim_var'](upper_name, value) new_value = __salt__['makeconf.get_var'](upper_name) # TODO verify appends and trims worked ret['changes'] = {upper_name: {'old': old_value, 'new': new_value}} msg = 'Variable {0} is correct in make.conf' ret['comment'] = msg.format(name) # Now finally return return ret
Verify that the variable is in the ``make.conf`` and has the provided settings. If value is set, contains and excludes will be ignored. name The variable name. This will automatically be converted to upper case since variables in ``make.conf`` are in upper case value Enforce that the value of the variable is set to the provided value contains Enforce that the value of the variable contains the provided value excludes Enforce that the value of the variable does not contain the provided value.
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/makeconf.py#L41-L162
[ "def _make_set(var):\n '''\n Force var to be a set\n '''\n if var is None:\n return set()\n if not isinstance(var, list):\n if isinstance(var, six.string_types):\n var = var.split()\n else:\n var = list(var)\n return set(var)\n" ]
# -*- coding: utf-8 -*- ''' Management of Gentoo make.conf ============================== A state module to manage Gentoo's ``make.conf`` file .. code-block:: yaml makeopts: makeconf.present: - value: '-j3' ''' from __future__ import absolute_import, print_function, unicode_literals # Import 3rd-party libs from salt.ext import six def __virtual__(): ''' Only load if the makeconf module is available in __salt__ ''' return 'makeconf' if 'makeconf.get_var' in __salt__ else False def _make_set(var): ''' Force var to be a set ''' if var is None: return set() if not isinstance(var, list): if isinstance(var, six.string_types): var = var.split() else: var = list(var) return set(var) def absent(name): ''' Verify that the variable is not in the ``make.conf``. name The variable name. This will automatically be converted to upper case since variables in ``make.conf`` are in upper case ''' ret = {'changes': {}, 'comment': '', 'name': name, 'result': True} # Make name all Uppers since make.conf uses all Upper vars upper_name = name.upper() old_value = __salt__['makeconf.get_var'](upper_name) if old_value is None: msg = 'Variable {0} is already absent from make.conf' ret['comment'] = msg.format(name) else: if __opts__['test']: msg = 'Variable {0} is set to be removed from make.conf' ret['comment'] = msg.format(name) ret['result'] = None else: __salt__['makeconf.remove_var'](upper_name) new_value = __salt__['makeconf.get_var'](upper_name) if new_value is not None: msg = 'Variable {0} failed to be removed from make.conf' ret['comment'] = msg.format(name) ret['result'] = False else: msg = 'Variable {0} was removed from make.conf' ret['comment'] = msg.format(name) ret['result'] = True return ret
saltstack/salt
salt/states/makeconf.py
absent
python
def absent(name): ''' Verify that the variable is not in the ``make.conf``. name The variable name. This will automatically be converted to upper case since variables in ``make.conf`` are in upper case ''' ret = {'changes': {}, 'comment': '', 'name': name, 'result': True} # Make name all Uppers since make.conf uses all Upper vars upper_name = name.upper() old_value = __salt__['makeconf.get_var'](upper_name) if old_value is None: msg = 'Variable {0} is already absent from make.conf' ret['comment'] = msg.format(name) else: if __opts__['test']: msg = 'Variable {0} is set to be removed from make.conf' ret['comment'] = msg.format(name) ret['result'] = None else: __salt__['makeconf.remove_var'](upper_name) new_value = __salt__['makeconf.get_var'](upper_name) if new_value is not None: msg = 'Variable {0} failed to be removed from make.conf' ret['comment'] = msg.format(name) ret['result'] = False else: msg = 'Variable {0} was removed from make.conf' ret['comment'] = msg.format(name) ret['result'] = True return ret
Verify that the variable is not in the ``make.conf``. name The variable name. This will automatically be converted to upper case since variables in ``make.conf`` are in upper case
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/states/makeconf.py#L165-L203
null
# -*- coding: utf-8 -*- ''' Management of Gentoo make.conf ============================== A state module to manage Gentoo's ``make.conf`` file .. code-block:: yaml makeopts: makeconf.present: - value: '-j3' ''' from __future__ import absolute_import, print_function, unicode_literals # Import 3rd-party libs from salt.ext import six def __virtual__(): ''' Only load if the makeconf module is available in __salt__ ''' return 'makeconf' if 'makeconf.get_var' in __salt__ else False def _make_set(var): ''' Force var to be a set ''' if var is None: return set() if not isinstance(var, list): if isinstance(var, six.string_types): var = var.split() else: var = list(var) return set(var) def present(name, value=None, contains=None, excludes=None): ''' Verify that the variable is in the ``make.conf`` and has the provided settings. If value is set, contains and excludes will be ignored. name The variable name. This will automatically be converted to upper case since variables in ``make.conf`` are in upper case value Enforce that the value of the variable is set to the provided value contains Enforce that the value of the variable contains the provided value excludes Enforce that the value of the variable does not contain the provided value. ''' ret = {'changes': {}, 'comment': '', 'name': name, 'result': True} # Make name all Uppers since make.conf uses all Upper vars upper_name = name.upper() old_value = __salt__['makeconf.get_var'](upper_name) # If only checking if variable is present allows for setting the # variable outside of salt states, but the state can still ensure # that is exists if value is None and contains is None and excludes is None: # variable is present if old_value is not None: msg = 'Variable {0} is already present in make.conf' ret['comment'] = msg.format(name) else: if __opts__['test']: msg = 'Variable {0} is to be set in make.conf' ret['comment'] = msg.format(name) ret['result'] = None else: changes = __salt__['makeconf.set_var'](upper_name, '') # If failed to be set if changes[upper_name]['new'] is None: msg = 'Variable {0} failed to be set in make.conf' ret['comment'] = msg.format(name) ret['result'] = False else: msg = 'Variable {0} set in make.conf' ret['comment'] = msg.format(name) elif value is not None: # variable is present and is set to value if old_value is not None and old_value == value: msg = 'Variable {0} is already "{1}" in make.conf' ret['comment'] = msg.format(name, value) else: if __opts__['test']: msg = 'Variable {0} is to be set to "{1}" in make.conf' ret['comment'] = msg.format(name, value) ret['result'] = None else: changes = __salt__['makeconf.set_var'](upper_name, value) # If failed to be set new_value = __salt__['makeconf.get_var'](upper_name) if new_value is None or new_value != value: msg = 'Variable {0} failed to be set in make.conf' ret['comment'] = msg.format(name) ret['result'] = False else: msg = 'Variable {0} is set in make.conf' ret['changes'] = changes ret['comment'] = msg.format(name) elif contains is not None or excludes is not None: # Make these into sets to easily compare things contains_set = _make_set(contains) excludes_set = _make_set(excludes) old_value_set = _make_set(old_value) if contains_set.intersection(excludes_set): msg = 'Variable {0} cannot contain and exclude the same value' ret['comment'] = msg.format(name) ret['result'] = False else: to_append = set() to_trim = set() if contains is not None: to_append = contains_set.difference(old_value_set) if excludes is not None: to_trim = excludes_set.intersection(old_value_set) if not to_append and not to_trim: msg = 'Variable {0} is correct in make.conf' ret['comment'] = msg.format(name) else: if __opts__['test']: msg = 'Variable {0} is set to'.format(name) if to_append: msg += ' append "{0}"'.format(list(to_append)) if to_trim: msg += ' trim "{0}"'.format(list(to_trim)) msg += ' in make.conf' ret['comment'] = msg ret['result'] = None else: for value in to_append: __salt__['makeconf.append_var'](upper_name, value) for value in to_trim: __salt__['makeconf.trim_var'](upper_name, value) new_value = __salt__['makeconf.get_var'](upper_name) # TODO verify appends and trims worked ret['changes'] = {upper_name: {'old': old_value, 'new': new_value}} msg = 'Variable {0} is correct in make.conf' ret['comment'] = msg.format(name) # Now finally return return ret
saltstack/salt
salt/modules/solaris_shadow.py
info
python
def info(name): ''' Return information for the specified user CLI Example: .. code-block:: bash salt '*' shadow.info root ''' if HAS_SPWD: try: data = spwd.getspnam(name) ret = { 'name': data.sp_nam, 'passwd': data.sp_pwd, 'lstchg': data.sp_lstchg, 'min': data.sp_min, 'max': data.sp_max, 'warn': data.sp_warn, 'inact': data.sp_inact, 'expire': data.sp_expire} except KeyError: ret = { 'name': '', 'passwd': '', 'lstchg': '', 'min': '', 'max': '', 'warn': '', 'inact': '', 'expire': ''} return ret # SmartOS joyent_20130322T181205Z does not have spwd, but not all is lost # Return what we can know ret = { 'name': '', 'passwd': '', 'lstchg': '', 'min': '', 'max': '', 'warn': '', 'inact': '', 'expire': ''} try: data = pwd.getpwnam(name) ret.update({ 'name': name }) except KeyError: return ret # To compensate for lack of spwd module, read in password hash from /etc/shadow s_file = '/etc/shadow' if not os.path.isfile(s_file): return ret with salt.utils.files.fopen(s_file, 'rb') as ifile: for line in ifile: comps = line.strip().split(':') if comps[0] == name: ret.update({'passwd': comps[1]}) # For SmartOS `passwd -s <username>` and the output format is: # name status mm/dd/yy min max warn # # Fields: # 1. Name: username # 2. Status: # - LK: locked # - NL: no login # - NP: No password # - PS: Password # 3. Last password change # 4. Minimum age # 5. Maximum age # 6. Warning period output = __salt__['cmd.run_all']('passwd -s {0}'.format(name), python_shell=False) if output['retcode'] != 0: return ret fields = output['stdout'].split() if len(fields) == 2: # For example: # root NL return ret # We have all fields: # buildbot L 05/09/2013 0 99999 7 ret.update({ 'name': data.pw_name, 'lstchg': fields[2], 'min': int(fields[3]), 'max': int(fields[4]), 'warn': int(fields[5]), 'inact': '', 'expire': '' }) return ret
Return information for the specified user CLI Example: .. code-block:: bash salt '*' shadow.info root
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/solaris_shadow.py#L62-L161
[ "def fopen(*args, **kwargs):\n '''\n Wrapper around open() built-in to set CLOEXEC on the fd.\n\n This flag specifies that the file descriptor should be closed when an exec\n function is invoked;\n\n When a file descriptor is allocated (as with open or dup), this bit is\n initially cleared on the new file descriptor, meaning that descriptor will\n survive into the new program after exec.\n\n NB! We still have small race condition between open and fcntl.\n '''\n if six.PY3:\n try:\n # Don't permit stdin/stdout/stderr to be opened. The boolean False\n # and True are treated by Python 3's open() as file descriptors 0\n # and 1, respectively.\n if args[0] in (0, 1, 2):\n raise TypeError(\n '{0} is not a permitted file descriptor'.format(args[0])\n )\n except IndexError:\n pass\n binary = None\n # ensure 'binary' mode is always used on Windows in Python 2\n if ((six.PY2 and salt.utils.platform.is_windows() and 'binary' not in kwargs) or\n kwargs.pop('binary', False)):\n if len(args) > 1:\n args = list(args)\n if 'b' not in args[1]:\n args[1] = args[1].replace('t', 'b')\n if 'b' not in args[1]:\n args[1] += 'b'\n elif kwargs.get('mode'):\n if 'b' not in kwargs['mode']:\n kwargs['mode'] = kwargs['mode'].replace('t', 'b')\n if 'b' not in kwargs['mode']:\n kwargs['mode'] += 'b'\n else:\n # the default is to read\n kwargs['mode'] = 'rb'\n elif six.PY3 and 'encoding' not in kwargs:\n # In Python 3, if text mode is used and the encoding\n # is not specified, set the encoding to 'utf-8'.\n binary = False\n if len(args) > 1:\n args = list(args)\n if 'b' in args[1]:\n binary = True\n if kwargs.get('mode', None):\n if 'b' in kwargs['mode']:\n binary = True\n if not binary:\n kwargs['encoding'] = __salt_system_encoding__\n\n if six.PY3 and not binary and not kwargs.get('newline', None):\n kwargs['newline'] = ''\n\n f_handle = open(*args, **kwargs) # pylint: disable=resource-leakage\n\n if is_fcntl_available():\n # modify the file descriptor on systems with fcntl\n # unix and unix-like systems only\n try:\n FD_CLOEXEC = fcntl.FD_CLOEXEC # pylint: disable=C0103\n except AttributeError:\n FD_CLOEXEC = 1 # pylint: disable=C0103\n old_flags = fcntl.fcntl(f_handle.fileno(), fcntl.F_GETFD)\n fcntl.fcntl(f_handle.fileno(), fcntl.F_SETFD, old_flags | FD_CLOEXEC)\n\n return f_handle\n" ]
# -*- coding: utf-8 -*- ''' Manage the password database on Solaris systems .. important:: If you feel that Salt should be using this module to manage passwords on a minion, and it is using a different module (or gives an error similar to *'shadow.info' is not available*), see :ref:`here <module-provider-override>`. ''' from __future__ import absolute_import, unicode_literals, print_function # Import python libs import os try: import spwd HAS_SPWD = True except ImportError: # SmartOS joyent_20130322T181205Z does not have spwd HAS_SPWD = False try: import pwd except ImportError: pass # We're most likely on a Windows machine. # Import salt libs import salt.utils.files from salt.exceptions import CommandExecutionError try: import salt.utils.pycrypto HAS_CRYPT = True except ImportError: HAS_CRYPT = False # Define the module's virtual name __virtualname__ = 'shadow' def __virtual__(): ''' Only work on POSIX-like systems ''' if __grains__.get('kernel', '') == 'SunOS': return __virtualname__ return (False, 'The solaris_shadow execution module failed to load: only available on Solaris systems.') def default_hash(): ''' Returns the default hash used for unset passwords CLI Example: .. code-block:: bash salt '*' shadow.default_hash ''' return '!' def set_maxdays(name, maxdays): ''' Set the maximum number of days during which a password is valid. See man passwd. CLI Example: .. code-block:: bash salt '*' shadow.set_maxdays username 90 ''' pre_info = info(name) if maxdays == pre_info['max']: return True cmd = 'passwd -x {0} {1}'.format(maxdays, name) __salt__['cmd.run'](cmd, python_shell=False) post_info = info(name) if post_info['max'] != pre_info['max']: return post_info['max'] == maxdays def set_mindays(name, mindays): ''' Set the minimum number of days between password changes. See man passwd. CLI Example: .. code-block:: bash salt '*' shadow.set_mindays username 7 ''' pre_info = info(name) if mindays == pre_info['min']: return True cmd = 'passwd -n {0} {1}'.format(mindays, name) __salt__['cmd.run'](cmd, python_shell=False) post_info = info(name) if post_info['min'] != pre_info['min']: return post_info['min'] == mindays return False def gen_password(password, crypt_salt=None, algorithm='sha512'): ''' .. versionadded:: 2015.8.8 Generate hashed password .. note:: When called this function is called directly via remote-execution, the password argument may be displayed in the system's process list. This may be a security risk on certain systems. password Plaintext password to be hashed. crypt_salt Crpytographic salt. If not given, a random 8-character salt will be generated. algorithm The following hash algorithms are supported: * md5 * blowfish (not in mainline glibc, only available in distros that add it) * sha256 * sha512 (default) CLI Example: .. code-block:: bash salt '*' shadow.gen_password 'I_am_password' salt '*' shadow.gen_password 'I_am_password' crypt_salt='I_am_salt' algorithm=sha256 ''' if not HAS_CRYPT: raise CommandExecutionError( 'gen_password is not available on this operating system ' 'because the "crypt" python module is not available.' ) return salt.utils.pycrypto.gen_hash(crypt_salt, password, algorithm) def del_password(name): ''' .. versionadded:: 2015.8.8 Delete the password from name user CLI Example: .. code-block:: bash salt '*' shadow.del_password username ''' cmd = 'passwd -d {0}'.format(name) __salt__['cmd.run'](cmd, python_shell=False, output_loglevel='quiet') uinfo = info(name) return not uinfo['passwd'] def set_password(name, password): ''' Set the password for a named user. The password must be a properly defined hash, the password hash can be generated with this command: ``openssl passwd -1 <plaintext password>`` CLI Example: .. code-block:: bash salt '*' shadow.set_password root $1$UYCIxa628.9qXjpQCjM4a.. ''' s_file = '/etc/shadow' ret = {} if not os.path.isfile(s_file): return ret lines = [] with salt.utils.files.fopen(s_file, 'rb') as ifile: for line in ifile: comps = line.strip().split(':') if comps[0] != name: lines.append(line) continue comps[1] = password line = ':'.join(comps) lines.append('{0}\n'.format(line)) with salt.utils.files.fopen(s_file, 'w+') as ofile: lines = [salt.utils.stringutils.to_str(_l) for _l in lines] ofile.writelines(lines) uinfo = info(name) return uinfo['passwd'] == password def set_warndays(name, warndays): ''' Set the number of days of warning before a password change is required. See man passwd. CLI Example: .. code-block:: bash salt '*' shadow.set_warndays username 7 ''' pre_info = info(name) if warndays == pre_info['warn']: return True cmd = 'passwd -w {0} {1}'.format(warndays, name) __salt__['cmd.run'](cmd, python_shell=False) post_info = info(name) if post_info['warn'] != pre_info['warn']: return post_info['warn'] == warndays return False
saltstack/salt
salt/modules/solaris_shadow.py
set_maxdays
python
def set_maxdays(name, maxdays): ''' Set the maximum number of days during which a password is valid. See man passwd. CLI Example: .. code-block:: bash salt '*' shadow.set_maxdays username 90 ''' pre_info = info(name) if maxdays == pre_info['max']: return True cmd = 'passwd -x {0} {1}'.format(maxdays, name) __salt__['cmd.run'](cmd, python_shell=False) post_info = info(name) if post_info['max'] != pre_info['max']: return post_info['max'] == maxdays
Set the maximum number of days during which a password is valid. See man passwd. CLI Example: .. code-block:: bash salt '*' shadow.set_maxdays username 90
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/solaris_shadow.py#L164-L182
[ "def info(name):\n '''\n Return information for the specified user\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' shadow.info root\n '''\n if HAS_SPWD:\n try:\n data = spwd.getspnam(name)\n ret = {\n 'name': data.sp_nam,\n 'passwd': data.sp_pwd,\n 'lstchg': data.sp_lstchg,\n 'min': data.sp_min,\n 'max': data.sp_max,\n 'warn': data.sp_warn,\n 'inact': data.sp_inact,\n 'expire': data.sp_expire}\n except KeyError:\n ret = {\n 'name': '',\n 'passwd': '',\n 'lstchg': '',\n 'min': '',\n 'max': '',\n 'warn': '',\n 'inact': '',\n 'expire': ''}\n return ret\n\n # SmartOS joyent_20130322T181205Z does not have spwd, but not all is lost\n # Return what we can know\n ret = {\n 'name': '',\n 'passwd': '',\n 'lstchg': '',\n 'min': '',\n 'max': '',\n 'warn': '',\n 'inact': '',\n 'expire': ''}\n\n try:\n data = pwd.getpwnam(name)\n ret.update({\n 'name': name\n })\n except KeyError:\n return ret\n\n # To compensate for lack of spwd module, read in password hash from /etc/shadow\n s_file = '/etc/shadow'\n if not os.path.isfile(s_file):\n return ret\n with salt.utils.files.fopen(s_file, 'rb') as ifile:\n for line in ifile:\n comps = line.strip().split(':')\n if comps[0] == name:\n ret.update({'passwd': comps[1]})\n\n # For SmartOS `passwd -s <username>` and the output format is:\n # name status mm/dd/yy min max warn\n #\n # Fields:\n # 1. Name: username\n # 2. Status:\n # - LK: locked\n # - NL: no login\n # - NP: No password\n # - PS: Password\n # 3. Last password change\n # 4. Minimum age\n # 5. Maximum age\n # 6. Warning period\n\n output = __salt__['cmd.run_all']('passwd -s {0}'.format(name), python_shell=False)\n if output['retcode'] != 0:\n return ret\n\n fields = output['stdout'].split()\n if len(fields) == 2:\n # For example:\n # root NL\n return ret\n # We have all fields:\n # buildbot L 05/09/2013 0 99999 7\n ret.update({\n 'name': data.pw_name,\n 'lstchg': fields[2],\n 'min': int(fields[3]),\n 'max': int(fields[4]),\n 'warn': int(fields[5]),\n 'inact': '',\n 'expire': ''\n })\n return ret\n" ]
# -*- coding: utf-8 -*- ''' Manage the password database on Solaris systems .. important:: If you feel that Salt should be using this module to manage passwords on a minion, and it is using a different module (or gives an error similar to *'shadow.info' is not available*), see :ref:`here <module-provider-override>`. ''' from __future__ import absolute_import, unicode_literals, print_function # Import python libs import os try: import spwd HAS_SPWD = True except ImportError: # SmartOS joyent_20130322T181205Z does not have spwd HAS_SPWD = False try: import pwd except ImportError: pass # We're most likely on a Windows machine. # Import salt libs import salt.utils.files from salt.exceptions import CommandExecutionError try: import salt.utils.pycrypto HAS_CRYPT = True except ImportError: HAS_CRYPT = False # Define the module's virtual name __virtualname__ = 'shadow' def __virtual__(): ''' Only work on POSIX-like systems ''' if __grains__.get('kernel', '') == 'SunOS': return __virtualname__ return (False, 'The solaris_shadow execution module failed to load: only available on Solaris systems.') def default_hash(): ''' Returns the default hash used for unset passwords CLI Example: .. code-block:: bash salt '*' shadow.default_hash ''' return '!' def info(name): ''' Return information for the specified user CLI Example: .. code-block:: bash salt '*' shadow.info root ''' if HAS_SPWD: try: data = spwd.getspnam(name) ret = { 'name': data.sp_nam, 'passwd': data.sp_pwd, 'lstchg': data.sp_lstchg, 'min': data.sp_min, 'max': data.sp_max, 'warn': data.sp_warn, 'inact': data.sp_inact, 'expire': data.sp_expire} except KeyError: ret = { 'name': '', 'passwd': '', 'lstchg': '', 'min': '', 'max': '', 'warn': '', 'inact': '', 'expire': ''} return ret # SmartOS joyent_20130322T181205Z does not have spwd, but not all is lost # Return what we can know ret = { 'name': '', 'passwd': '', 'lstchg': '', 'min': '', 'max': '', 'warn': '', 'inact': '', 'expire': ''} try: data = pwd.getpwnam(name) ret.update({ 'name': name }) except KeyError: return ret # To compensate for lack of spwd module, read in password hash from /etc/shadow s_file = '/etc/shadow' if not os.path.isfile(s_file): return ret with salt.utils.files.fopen(s_file, 'rb') as ifile: for line in ifile: comps = line.strip().split(':') if comps[0] == name: ret.update({'passwd': comps[1]}) # For SmartOS `passwd -s <username>` and the output format is: # name status mm/dd/yy min max warn # # Fields: # 1. Name: username # 2. Status: # - LK: locked # - NL: no login # - NP: No password # - PS: Password # 3. Last password change # 4. Minimum age # 5. Maximum age # 6. Warning period output = __salt__['cmd.run_all']('passwd -s {0}'.format(name), python_shell=False) if output['retcode'] != 0: return ret fields = output['stdout'].split() if len(fields) == 2: # For example: # root NL return ret # We have all fields: # buildbot L 05/09/2013 0 99999 7 ret.update({ 'name': data.pw_name, 'lstchg': fields[2], 'min': int(fields[3]), 'max': int(fields[4]), 'warn': int(fields[5]), 'inact': '', 'expire': '' }) return ret def set_mindays(name, mindays): ''' Set the minimum number of days between password changes. See man passwd. CLI Example: .. code-block:: bash salt '*' shadow.set_mindays username 7 ''' pre_info = info(name) if mindays == pre_info['min']: return True cmd = 'passwd -n {0} {1}'.format(mindays, name) __salt__['cmd.run'](cmd, python_shell=False) post_info = info(name) if post_info['min'] != pre_info['min']: return post_info['min'] == mindays return False def gen_password(password, crypt_salt=None, algorithm='sha512'): ''' .. versionadded:: 2015.8.8 Generate hashed password .. note:: When called this function is called directly via remote-execution, the password argument may be displayed in the system's process list. This may be a security risk on certain systems. password Plaintext password to be hashed. crypt_salt Crpytographic salt. If not given, a random 8-character salt will be generated. algorithm The following hash algorithms are supported: * md5 * blowfish (not in mainline glibc, only available in distros that add it) * sha256 * sha512 (default) CLI Example: .. code-block:: bash salt '*' shadow.gen_password 'I_am_password' salt '*' shadow.gen_password 'I_am_password' crypt_salt='I_am_salt' algorithm=sha256 ''' if not HAS_CRYPT: raise CommandExecutionError( 'gen_password is not available on this operating system ' 'because the "crypt" python module is not available.' ) return salt.utils.pycrypto.gen_hash(crypt_salt, password, algorithm) def del_password(name): ''' .. versionadded:: 2015.8.8 Delete the password from name user CLI Example: .. code-block:: bash salt '*' shadow.del_password username ''' cmd = 'passwd -d {0}'.format(name) __salt__['cmd.run'](cmd, python_shell=False, output_loglevel='quiet') uinfo = info(name) return not uinfo['passwd'] def set_password(name, password): ''' Set the password for a named user. The password must be a properly defined hash, the password hash can be generated with this command: ``openssl passwd -1 <plaintext password>`` CLI Example: .. code-block:: bash salt '*' shadow.set_password root $1$UYCIxa628.9qXjpQCjM4a.. ''' s_file = '/etc/shadow' ret = {} if not os.path.isfile(s_file): return ret lines = [] with salt.utils.files.fopen(s_file, 'rb') as ifile: for line in ifile: comps = line.strip().split(':') if comps[0] != name: lines.append(line) continue comps[1] = password line = ':'.join(comps) lines.append('{0}\n'.format(line)) with salt.utils.files.fopen(s_file, 'w+') as ofile: lines = [salt.utils.stringutils.to_str(_l) for _l in lines] ofile.writelines(lines) uinfo = info(name) return uinfo['passwd'] == password def set_warndays(name, warndays): ''' Set the number of days of warning before a password change is required. See man passwd. CLI Example: .. code-block:: bash salt '*' shadow.set_warndays username 7 ''' pre_info = info(name) if warndays == pre_info['warn']: return True cmd = 'passwd -w {0} {1}'.format(warndays, name) __salt__['cmd.run'](cmd, python_shell=False) post_info = info(name) if post_info['warn'] != pre_info['warn']: return post_info['warn'] == warndays return False
saltstack/salt
salt/modules/solaris_shadow.py
set_mindays
python
def set_mindays(name, mindays): ''' Set the minimum number of days between password changes. See man passwd. CLI Example: .. code-block:: bash salt '*' shadow.set_mindays username 7 ''' pre_info = info(name) if mindays == pre_info['min']: return True cmd = 'passwd -n {0} {1}'.format(mindays, name) __salt__['cmd.run'](cmd, python_shell=False) post_info = info(name) if post_info['min'] != pre_info['min']: return post_info['min'] == mindays return False
Set the minimum number of days between password changes. See man passwd. CLI Example: .. code-block:: bash salt '*' shadow.set_mindays username 7
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/solaris_shadow.py#L185-L203
[ "def info(name):\n '''\n Return information for the specified user\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' shadow.info root\n '''\n if HAS_SPWD:\n try:\n data = spwd.getspnam(name)\n ret = {\n 'name': data.sp_nam,\n 'passwd': data.sp_pwd,\n 'lstchg': data.sp_lstchg,\n 'min': data.sp_min,\n 'max': data.sp_max,\n 'warn': data.sp_warn,\n 'inact': data.sp_inact,\n 'expire': data.sp_expire}\n except KeyError:\n ret = {\n 'name': '',\n 'passwd': '',\n 'lstchg': '',\n 'min': '',\n 'max': '',\n 'warn': '',\n 'inact': '',\n 'expire': ''}\n return ret\n\n # SmartOS joyent_20130322T181205Z does not have spwd, but not all is lost\n # Return what we can know\n ret = {\n 'name': '',\n 'passwd': '',\n 'lstchg': '',\n 'min': '',\n 'max': '',\n 'warn': '',\n 'inact': '',\n 'expire': ''}\n\n try:\n data = pwd.getpwnam(name)\n ret.update({\n 'name': name\n })\n except KeyError:\n return ret\n\n # To compensate for lack of spwd module, read in password hash from /etc/shadow\n s_file = '/etc/shadow'\n if not os.path.isfile(s_file):\n return ret\n with salt.utils.files.fopen(s_file, 'rb') as ifile:\n for line in ifile:\n comps = line.strip().split(':')\n if comps[0] == name:\n ret.update({'passwd': comps[1]})\n\n # For SmartOS `passwd -s <username>` and the output format is:\n # name status mm/dd/yy min max warn\n #\n # Fields:\n # 1. Name: username\n # 2. Status:\n # - LK: locked\n # - NL: no login\n # - NP: No password\n # - PS: Password\n # 3. Last password change\n # 4. Minimum age\n # 5. Maximum age\n # 6. Warning period\n\n output = __salt__['cmd.run_all']('passwd -s {0}'.format(name), python_shell=False)\n if output['retcode'] != 0:\n return ret\n\n fields = output['stdout'].split()\n if len(fields) == 2:\n # For example:\n # root NL\n return ret\n # We have all fields:\n # buildbot L 05/09/2013 0 99999 7\n ret.update({\n 'name': data.pw_name,\n 'lstchg': fields[2],\n 'min': int(fields[3]),\n 'max': int(fields[4]),\n 'warn': int(fields[5]),\n 'inact': '',\n 'expire': ''\n })\n return ret\n" ]
# -*- coding: utf-8 -*- ''' Manage the password database on Solaris systems .. important:: If you feel that Salt should be using this module to manage passwords on a minion, and it is using a different module (or gives an error similar to *'shadow.info' is not available*), see :ref:`here <module-provider-override>`. ''' from __future__ import absolute_import, unicode_literals, print_function # Import python libs import os try: import spwd HAS_SPWD = True except ImportError: # SmartOS joyent_20130322T181205Z does not have spwd HAS_SPWD = False try: import pwd except ImportError: pass # We're most likely on a Windows machine. # Import salt libs import salt.utils.files from salt.exceptions import CommandExecutionError try: import salt.utils.pycrypto HAS_CRYPT = True except ImportError: HAS_CRYPT = False # Define the module's virtual name __virtualname__ = 'shadow' def __virtual__(): ''' Only work on POSIX-like systems ''' if __grains__.get('kernel', '') == 'SunOS': return __virtualname__ return (False, 'The solaris_shadow execution module failed to load: only available on Solaris systems.') def default_hash(): ''' Returns the default hash used for unset passwords CLI Example: .. code-block:: bash salt '*' shadow.default_hash ''' return '!' def info(name): ''' Return information for the specified user CLI Example: .. code-block:: bash salt '*' shadow.info root ''' if HAS_SPWD: try: data = spwd.getspnam(name) ret = { 'name': data.sp_nam, 'passwd': data.sp_pwd, 'lstchg': data.sp_lstchg, 'min': data.sp_min, 'max': data.sp_max, 'warn': data.sp_warn, 'inact': data.sp_inact, 'expire': data.sp_expire} except KeyError: ret = { 'name': '', 'passwd': '', 'lstchg': '', 'min': '', 'max': '', 'warn': '', 'inact': '', 'expire': ''} return ret # SmartOS joyent_20130322T181205Z does not have spwd, but not all is lost # Return what we can know ret = { 'name': '', 'passwd': '', 'lstchg': '', 'min': '', 'max': '', 'warn': '', 'inact': '', 'expire': ''} try: data = pwd.getpwnam(name) ret.update({ 'name': name }) except KeyError: return ret # To compensate for lack of spwd module, read in password hash from /etc/shadow s_file = '/etc/shadow' if not os.path.isfile(s_file): return ret with salt.utils.files.fopen(s_file, 'rb') as ifile: for line in ifile: comps = line.strip().split(':') if comps[0] == name: ret.update({'passwd': comps[1]}) # For SmartOS `passwd -s <username>` and the output format is: # name status mm/dd/yy min max warn # # Fields: # 1. Name: username # 2. Status: # - LK: locked # - NL: no login # - NP: No password # - PS: Password # 3. Last password change # 4. Minimum age # 5. Maximum age # 6. Warning period output = __salt__['cmd.run_all']('passwd -s {0}'.format(name), python_shell=False) if output['retcode'] != 0: return ret fields = output['stdout'].split() if len(fields) == 2: # For example: # root NL return ret # We have all fields: # buildbot L 05/09/2013 0 99999 7 ret.update({ 'name': data.pw_name, 'lstchg': fields[2], 'min': int(fields[3]), 'max': int(fields[4]), 'warn': int(fields[5]), 'inact': '', 'expire': '' }) return ret def set_maxdays(name, maxdays): ''' Set the maximum number of days during which a password is valid. See man passwd. CLI Example: .. code-block:: bash salt '*' shadow.set_maxdays username 90 ''' pre_info = info(name) if maxdays == pre_info['max']: return True cmd = 'passwd -x {0} {1}'.format(maxdays, name) __salt__['cmd.run'](cmd, python_shell=False) post_info = info(name) if post_info['max'] != pre_info['max']: return post_info['max'] == maxdays def gen_password(password, crypt_salt=None, algorithm='sha512'): ''' .. versionadded:: 2015.8.8 Generate hashed password .. note:: When called this function is called directly via remote-execution, the password argument may be displayed in the system's process list. This may be a security risk on certain systems. password Plaintext password to be hashed. crypt_salt Crpytographic salt. If not given, a random 8-character salt will be generated. algorithm The following hash algorithms are supported: * md5 * blowfish (not in mainline glibc, only available in distros that add it) * sha256 * sha512 (default) CLI Example: .. code-block:: bash salt '*' shadow.gen_password 'I_am_password' salt '*' shadow.gen_password 'I_am_password' crypt_salt='I_am_salt' algorithm=sha256 ''' if not HAS_CRYPT: raise CommandExecutionError( 'gen_password is not available on this operating system ' 'because the "crypt" python module is not available.' ) return salt.utils.pycrypto.gen_hash(crypt_salt, password, algorithm) def del_password(name): ''' .. versionadded:: 2015.8.8 Delete the password from name user CLI Example: .. code-block:: bash salt '*' shadow.del_password username ''' cmd = 'passwd -d {0}'.format(name) __salt__['cmd.run'](cmd, python_shell=False, output_loglevel='quiet') uinfo = info(name) return not uinfo['passwd'] def set_password(name, password): ''' Set the password for a named user. The password must be a properly defined hash, the password hash can be generated with this command: ``openssl passwd -1 <plaintext password>`` CLI Example: .. code-block:: bash salt '*' shadow.set_password root $1$UYCIxa628.9qXjpQCjM4a.. ''' s_file = '/etc/shadow' ret = {} if not os.path.isfile(s_file): return ret lines = [] with salt.utils.files.fopen(s_file, 'rb') as ifile: for line in ifile: comps = line.strip().split(':') if comps[0] != name: lines.append(line) continue comps[1] = password line = ':'.join(comps) lines.append('{0}\n'.format(line)) with salt.utils.files.fopen(s_file, 'w+') as ofile: lines = [salt.utils.stringutils.to_str(_l) for _l in lines] ofile.writelines(lines) uinfo = info(name) return uinfo['passwd'] == password def set_warndays(name, warndays): ''' Set the number of days of warning before a password change is required. See man passwd. CLI Example: .. code-block:: bash salt '*' shadow.set_warndays username 7 ''' pre_info = info(name) if warndays == pre_info['warn']: return True cmd = 'passwd -w {0} {1}'.format(warndays, name) __salt__['cmd.run'](cmd, python_shell=False) post_info = info(name) if post_info['warn'] != pre_info['warn']: return post_info['warn'] == warndays return False
saltstack/salt
salt/modules/solaris_shadow.py
del_password
python
def del_password(name): ''' .. versionadded:: 2015.8.8 Delete the password from name user CLI Example: .. code-block:: bash salt '*' shadow.del_password username ''' cmd = 'passwd -d {0}'.format(name) __salt__['cmd.run'](cmd, python_shell=False, output_loglevel='quiet') uinfo = info(name) return not uinfo['passwd']
.. versionadded:: 2015.8.8 Delete the password from name user CLI Example: .. code-block:: bash salt '*' shadow.del_password username
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/solaris_shadow.py#L248-L263
[ "def info(name):\n '''\n Return information for the specified user\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' shadow.info root\n '''\n if HAS_SPWD:\n try:\n data = spwd.getspnam(name)\n ret = {\n 'name': data.sp_nam,\n 'passwd': data.sp_pwd,\n 'lstchg': data.sp_lstchg,\n 'min': data.sp_min,\n 'max': data.sp_max,\n 'warn': data.sp_warn,\n 'inact': data.sp_inact,\n 'expire': data.sp_expire}\n except KeyError:\n ret = {\n 'name': '',\n 'passwd': '',\n 'lstchg': '',\n 'min': '',\n 'max': '',\n 'warn': '',\n 'inact': '',\n 'expire': ''}\n return ret\n\n # SmartOS joyent_20130322T181205Z does not have spwd, but not all is lost\n # Return what we can know\n ret = {\n 'name': '',\n 'passwd': '',\n 'lstchg': '',\n 'min': '',\n 'max': '',\n 'warn': '',\n 'inact': '',\n 'expire': ''}\n\n try:\n data = pwd.getpwnam(name)\n ret.update({\n 'name': name\n })\n except KeyError:\n return ret\n\n # To compensate for lack of spwd module, read in password hash from /etc/shadow\n s_file = '/etc/shadow'\n if not os.path.isfile(s_file):\n return ret\n with salt.utils.files.fopen(s_file, 'rb') as ifile:\n for line in ifile:\n comps = line.strip().split(':')\n if comps[0] == name:\n ret.update({'passwd': comps[1]})\n\n # For SmartOS `passwd -s <username>` and the output format is:\n # name status mm/dd/yy min max warn\n #\n # Fields:\n # 1. Name: username\n # 2. Status:\n # - LK: locked\n # - NL: no login\n # - NP: No password\n # - PS: Password\n # 3. Last password change\n # 4. Minimum age\n # 5. Maximum age\n # 6. Warning period\n\n output = __salt__['cmd.run_all']('passwd -s {0}'.format(name), python_shell=False)\n if output['retcode'] != 0:\n return ret\n\n fields = output['stdout'].split()\n if len(fields) == 2:\n # For example:\n # root NL\n return ret\n # We have all fields:\n # buildbot L 05/09/2013 0 99999 7\n ret.update({\n 'name': data.pw_name,\n 'lstchg': fields[2],\n 'min': int(fields[3]),\n 'max': int(fields[4]),\n 'warn': int(fields[5]),\n 'inact': '',\n 'expire': ''\n })\n return ret\n" ]
# -*- coding: utf-8 -*- ''' Manage the password database on Solaris systems .. important:: If you feel that Salt should be using this module to manage passwords on a minion, and it is using a different module (or gives an error similar to *'shadow.info' is not available*), see :ref:`here <module-provider-override>`. ''' from __future__ import absolute_import, unicode_literals, print_function # Import python libs import os try: import spwd HAS_SPWD = True except ImportError: # SmartOS joyent_20130322T181205Z does not have spwd HAS_SPWD = False try: import pwd except ImportError: pass # We're most likely on a Windows machine. # Import salt libs import salt.utils.files from salt.exceptions import CommandExecutionError try: import salt.utils.pycrypto HAS_CRYPT = True except ImportError: HAS_CRYPT = False # Define the module's virtual name __virtualname__ = 'shadow' def __virtual__(): ''' Only work on POSIX-like systems ''' if __grains__.get('kernel', '') == 'SunOS': return __virtualname__ return (False, 'The solaris_shadow execution module failed to load: only available on Solaris systems.') def default_hash(): ''' Returns the default hash used for unset passwords CLI Example: .. code-block:: bash salt '*' shadow.default_hash ''' return '!' def info(name): ''' Return information for the specified user CLI Example: .. code-block:: bash salt '*' shadow.info root ''' if HAS_SPWD: try: data = spwd.getspnam(name) ret = { 'name': data.sp_nam, 'passwd': data.sp_pwd, 'lstchg': data.sp_lstchg, 'min': data.sp_min, 'max': data.sp_max, 'warn': data.sp_warn, 'inact': data.sp_inact, 'expire': data.sp_expire} except KeyError: ret = { 'name': '', 'passwd': '', 'lstchg': '', 'min': '', 'max': '', 'warn': '', 'inact': '', 'expire': ''} return ret # SmartOS joyent_20130322T181205Z does not have spwd, but not all is lost # Return what we can know ret = { 'name': '', 'passwd': '', 'lstchg': '', 'min': '', 'max': '', 'warn': '', 'inact': '', 'expire': ''} try: data = pwd.getpwnam(name) ret.update({ 'name': name }) except KeyError: return ret # To compensate for lack of spwd module, read in password hash from /etc/shadow s_file = '/etc/shadow' if not os.path.isfile(s_file): return ret with salt.utils.files.fopen(s_file, 'rb') as ifile: for line in ifile: comps = line.strip().split(':') if comps[0] == name: ret.update({'passwd': comps[1]}) # For SmartOS `passwd -s <username>` and the output format is: # name status mm/dd/yy min max warn # # Fields: # 1. Name: username # 2. Status: # - LK: locked # - NL: no login # - NP: No password # - PS: Password # 3. Last password change # 4. Minimum age # 5. Maximum age # 6. Warning period output = __salt__['cmd.run_all']('passwd -s {0}'.format(name), python_shell=False) if output['retcode'] != 0: return ret fields = output['stdout'].split() if len(fields) == 2: # For example: # root NL return ret # We have all fields: # buildbot L 05/09/2013 0 99999 7 ret.update({ 'name': data.pw_name, 'lstchg': fields[2], 'min': int(fields[3]), 'max': int(fields[4]), 'warn': int(fields[5]), 'inact': '', 'expire': '' }) return ret def set_maxdays(name, maxdays): ''' Set the maximum number of days during which a password is valid. See man passwd. CLI Example: .. code-block:: bash salt '*' shadow.set_maxdays username 90 ''' pre_info = info(name) if maxdays == pre_info['max']: return True cmd = 'passwd -x {0} {1}'.format(maxdays, name) __salt__['cmd.run'](cmd, python_shell=False) post_info = info(name) if post_info['max'] != pre_info['max']: return post_info['max'] == maxdays def set_mindays(name, mindays): ''' Set the minimum number of days between password changes. See man passwd. CLI Example: .. code-block:: bash salt '*' shadow.set_mindays username 7 ''' pre_info = info(name) if mindays == pre_info['min']: return True cmd = 'passwd -n {0} {1}'.format(mindays, name) __salt__['cmd.run'](cmd, python_shell=False) post_info = info(name) if post_info['min'] != pre_info['min']: return post_info['min'] == mindays return False def gen_password(password, crypt_salt=None, algorithm='sha512'): ''' .. versionadded:: 2015.8.8 Generate hashed password .. note:: When called this function is called directly via remote-execution, the password argument may be displayed in the system's process list. This may be a security risk on certain systems. password Plaintext password to be hashed. crypt_salt Crpytographic salt. If not given, a random 8-character salt will be generated. algorithm The following hash algorithms are supported: * md5 * blowfish (not in mainline glibc, only available in distros that add it) * sha256 * sha512 (default) CLI Example: .. code-block:: bash salt '*' shadow.gen_password 'I_am_password' salt '*' shadow.gen_password 'I_am_password' crypt_salt='I_am_salt' algorithm=sha256 ''' if not HAS_CRYPT: raise CommandExecutionError( 'gen_password is not available on this operating system ' 'because the "crypt" python module is not available.' ) return salt.utils.pycrypto.gen_hash(crypt_salt, password, algorithm) def set_password(name, password): ''' Set the password for a named user. The password must be a properly defined hash, the password hash can be generated with this command: ``openssl passwd -1 <plaintext password>`` CLI Example: .. code-block:: bash salt '*' shadow.set_password root $1$UYCIxa628.9qXjpQCjM4a.. ''' s_file = '/etc/shadow' ret = {} if not os.path.isfile(s_file): return ret lines = [] with salt.utils.files.fopen(s_file, 'rb') as ifile: for line in ifile: comps = line.strip().split(':') if comps[0] != name: lines.append(line) continue comps[1] = password line = ':'.join(comps) lines.append('{0}\n'.format(line)) with salt.utils.files.fopen(s_file, 'w+') as ofile: lines = [salt.utils.stringutils.to_str(_l) for _l in lines] ofile.writelines(lines) uinfo = info(name) return uinfo['passwd'] == password def set_warndays(name, warndays): ''' Set the number of days of warning before a password change is required. See man passwd. CLI Example: .. code-block:: bash salt '*' shadow.set_warndays username 7 ''' pre_info = info(name) if warndays == pre_info['warn']: return True cmd = 'passwd -w {0} {1}'.format(warndays, name) __salt__['cmd.run'](cmd, python_shell=False) post_info = info(name) if post_info['warn'] != pre_info['warn']: return post_info['warn'] == warndays return False
saltstack/salt
salt/modules/solaris_shadow.py
set_password
python
def set_password(name, password): ''' Set the password for a named user. The password must be a properly defined hash, the password hash can be generated with this command: ``openssl passwd -1 <plaintext password>`` CLI Example: .. code-block:: bash salt '*' shadow.set_password root $1$UYCIxa628.9qXjpQCjM4a.. ''' s_file = '/etc/shadow' ret = {} if not os.path.isfile(s_file): return ret lines = [] with salt.utils.files.fopen(s_file, 'rb') as ifile: for line in ifile: comps = line.strip().split(':') if comps[0] != name: lines.append(line) continue comps[1] = password line = ':'.join(comps) lines.append('{0}\n'.format(line)) with salt.utils.files.fopen(s_file, 'w+') as ofile: lines = [salt.utils.stringutils.to_str(_l) for _l in lines] ofile.writelines(lines) uinfo = info(name) return uinfo['passwd'] == password
Set the password for a named user. The password must be a properly defined hash, the password hash can be generated with this command: ``openssl passwd -1 <plaintext password>`` CLI Example: .. code-block:: bash salt '*' shadow.set_password root $1$UYCIxa628.9qXjpQCjM4a..
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/solaris_shadow.py#L266-L296
[ "def info(name):\n '''\n Return information for the specified user\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' shadow.info root\n '''\n if HAS_SPWD:\n try:\n data = spwd.getspnam(name)\n ret = {\n 'name': data.sp_nam,\n 'passwd': data.sp_pwd,\n 'lstchg': data.sp_lstchg,\n 'min': data.sp_min,\n 'max': data.sp_max,\n 'warn': data.sp_warn,\n 'inact': data.sp_inact,\n 'expire': data.sp_expire}\n except KeyError:\n ret = {\n 'name': '',\n 'passwd': '',\n 'lstchg': '',\n 'min': '',\n 'max': '',\n 'warn': '',\n 'inact': '',\n 'expire': ''}\n return ret\n\n # SmartOS joyent_20130322T181205Z does not have spwd, but not all is lost\n # Return what we can know\n ret = {\n 'name': '',\n 'passwd': '',\n 'lstchg': '',\n 'min': '',\n 'max': '',\n 'warn': '',\n 'inact': '',\n 'expire': ''}\n\n try:\n data = pwd.getpwnam(name)\n ret.update({\n 'name': name\n })\n except KeyError:\n return ret\n\n # To compensate for lack of spwd module, read in password hash from /etc/shadow\n s_file = '/etc/shadow'\n if not os.path.isfile(s_file):\n return ret\n with salt.utils.files.fopen(s_file, 'rb') as ifile:\n for line in ifile:\n comps = line.strip().split(':')\n if comps[0] == name:\n ret.update({'passwd': comps[1]})\n\n # For SmartOS `passwd -s <username>` and the output format is:\n # name status mm/dd/yy min max warn\n #\n # Fields:\n # 1. Name: username\n # 2. Status:\n # - LK: locked\n # - NL: no login\n # - NP: No password\n # - PS: Password\n # 3. Last password change\n # 4. Minimum age\n # 5. Maximum age\n # 6. Warning period\n\n output = __salt__['cmd.run_all']('passwd -s {0}'.format(name), python_shell=False)\n if output['retcode'] != 0:\n return ret\n\n fields = output['stdout'].split()\n if len(fields) == 2:\n # For example:\n # root NL\n return ret\n # We have all fields:\n # buildbot L 05/09/2013 0 99999 7\n ret.update({\n 'name': data.pw_name,\n 'lstchg': fields[2],\n 'min': int(fields[3]),\n 'max': int(fields[4]),\n 'warn': int(fields[5]),\n 'inact': '',\n 'expire': ''\n })\n return ret\n", "def fopen(*args, **kwargs):\n '''\n Wrapper around open() built-in to set CLOEXEC on the fd.\n\n This flag specifies that the file descriptor should be closed when an exec\n function is invoked;\n\n When a file descriptor is allocated (as with open or dup), this bit is\n initially cleared on the new file descriptor, meaning that descriptor will\n survive into the new program after exec.\n\n NB! We still have small race condition between open and fcntl.\n '''\n if six.PY3:\n try:\n # Don't permit stdin/stdout/stderr to be opened. The boolean False\n # and True are treated by Python 3's open() as file descriptors 0\n # and 1, respectively.\n if args[0] in (0, 1, 2):\n raise TypeError(\n '{0} is not a permitted file descriptor'.format(args[0])\n )\n except IndexError:\n pass\n binary = None\n # ensure 'binary' mode is always used on Windows in Python 2\n if ((six.PY2 and salt.utils.platform.is_windows() and 'binary' not in kwargs) or\n kwargs.pop('binary', False)):\n if len(args) > 1:\n args = list(args)\n if 'b' not in args[1]:\n args[1] = args[1].replace('t', 'b')\n if 'b' not in args[1]:\n args[1] += 'b'\n elif kwargs.get('mode'):\n if 'b' not in kwargs['mode']:\n kwargs['mode'] = kwargs['mode'].replace('t', 'b')\n if 'b' not in kwargs['mode']:\n kwargs['mode'] += 'b'\n else:\n # the default is to read\n kwargs['mode'] = 'rb'\n elif six.PY3 and 'encoding' not in kwargs:\n # In Python 3, if text mode is used and the encoding\n # is not specified, set the encoding to 'utf-8'.\n binary = False\n if len(args) > 1:\n args = list(args)\n if 'b' in args[1]:\n binary = True\n if kwargs.get('mode', None):\n if 'b' in kwargs['mode']:\n binary = True\n if not binary:\n kwargs['encoding'] = __salt_system_encoding__\n\n if six.PY3 and not binary and not kwargs.get('newline', None):\n kwargs['newline'] = ''\n\n f_handle = open(*args, **kwargs) # pylint: disable=resource-leakage\n\n if is_fcntl_available():\n # modify the file descriptor on systems with fcntl\n # unix and unix-like systems only\n try:\n FD_CLOEXEC = fcntl.FD_CLOEXEC # pylint: disable=C0103\n except AttributeError:\n FD_CLOEXEC = 1 # pylint: disable=C0103\n old_flags = fcntl.fcntl(f_handle.fileno(), fcntl.F_GETFD)\n fcntl.fcntl(f_handle.fileno(), fcntl.F_SETFD, old_flags | FD_CLOEXEC)\n\n return f_handle\n" ]
# -*- coding: utf-8 -*- ''' Manage the password database on Solaris systems .. important:: If you feel that Salt should be using this module to manage passwords on a minion, and it is using a different module (or gives an error similar to *'shadow.info' is not available*), see :ref:`here <module-provider-override>`. ''' from __future__ import absolute_import, unicode_literals, print_function # Import python libs import os try: import spwd HAS_SPWD = True except ImportError: # SmartOS joyent_20130322T181205Z does not have spwd HAS_SPWD = False try: import pwd except ImportError: pass # We're most likely on a Windows machine. # Import salt libs import salt.utils.files from salt.exceptions import CommandExecutionError try: import salt.utils.pycrypto HAS_CRYPT = True except ImportError: HAS_CRYPT = False # Define the module's virtual name __virtualname__ = 'shadow' def __virtual__(): ''' Only work on POSIX-like systems ''' if __grains__.get('kernel', '') == 'SunOS': return __virtualname__ return (False, 'The solaris_shadow execution module failed to load: only available on Solaris systems.') def default_hash(): ''' Returns the default hash used for unset passwords CLI Example: .. code-block:: bash salt '*' shadow.default_hash ''' return '!' def info(name): ''' Return information for the specified user CLI Example: .. code-block:: bash salt '*' shadow.info root ''' if HAS_SPWD: try: data = spwd.getspnam(name) ret = { 'name': data.sp_nam, 'passwd': data.sp_pwd, 'lstchg': data.sp_lstchg, 'min': data.sp_min, 'max': data.sp_max, 'warn': data.sp_warn, 'inact': data.sp_inact, 'expire': data.sp_expire} except KeyError: ret = { 'name': '', 'passwd': '', 'lstchg': '', 'min': '', 'max': '', 'warn': '', 'inact': '', 'expire': ''} return ret # SmartOS joyent_20130322T181205Z does not have spwd, but not all is lost # Return what we can know ret = { 'name': '', 'passwd': '', 'lstchg': '', 'min': '', 'max': '', 'warn': '', 'inact': '', 'expire': ''} try: data = pwd.getpwnam(name) ret.update({ 'name': name }) except KeyError: return ret # To compensate for lack of spwd module, read in password hash from /etc/shadow s_file = '/etc/shadow' if not os.path.isfile(s_file): return ret with salt.utils.files.fopen(s_file, 'rb') as ifile: for line in ifile: comps = line.strip().split(':') if comps[0] == name: ret.update({'passwd': comps[1]}) # For SmartOS `passwd -s <username>` and the output format is: # name status mm/dd/yy min max warn # # Fields: # 1. Name: username # 2. Status: # - LK: locked # - NL: no login # - NP: No password # - PS: Password # 3. Last password change # 4. Minimum age # 5. Maximum age # 6. Warning period output = __salt__['cmd.run_all']('passwd -s {0}'.format(name), python_shell=False) if output['retcode'] != 0: return ret fields = output['stdout'].split() if len(fields) == 2: # For example: # root NL return ret # We have all fields: # buildbot L 05/09/2013 0 99999 7 ret.update({ 'name': data.pw_name, 'lstchg': fields[2], 'min': int(fields[3]), 'max': int(fields[4]), 'warn': int(fields[5]), 'inact': '', 'expire': '' }) return ret def set_maxdays(name, maxdays): ''' Set the maximum number of days during which a password is valid. See man passwd. CLI Example: .. code-block:: bash salt '*' shadow.set_maxdays username 90 ''' pre_info = info(name) if maxdays == pre_info['max']: return True cmd = 'passwd -x {0} {1}'.format(maxdays, name) __salt__['cmd.run'](cmd, python_shell=False) post_info = info(name) if post_info['max'] != pre_info['max']: return post_info['max'] == maxdays def set_mindays(name, mindays): ''' Set the minimum number of days between password changes. See man passwd. CLI Example: .. code-block:: bash salt '*' shadow.set_mindays username 7 ''' pre_info = info(name) if mindays == pre_info['min']: return True cmd = 'passwd -n {0} {1}'.format(mindays, name) __salt__['cmd.run'](cmd, python_shell=False) post_info = info(name) if post_info['min'] != pre_info['min']: return post_info['min'] == mindays return False def gen_password(password, crypt_salt=None, algorithm='sha512'): ''' .. versionadded:: 2015.8.8 Generate hashed password .. note:: When called this function is called directly via remote-execution, the password argument may be displayed in the system's process list. This may be a security risk on certain systems. password Plaintext password to be hashed. crypt_salt Crpytographic salt. If not given, a random 8-character salt will be generated. algorithm The following hash algorithms are supported: * md5 * blowfish (not in mainline glibc, only available in distros that add it) * sha256 * sha512 (default) CLI Example: .. code-block:: bash salt '*' shadow.gen_password 'I_am_password' salt '*' shadow.gen_password 'I_am_password' crypt_salt='I_am_salt' algorithm=sha256 ''' if not HAS_CRYPT: raise CommandExecutionError( 'gen_password is not available on this operating system ' 'because the "crypt" python module is not available.' ) return salt.utils.pycrypto.gen_hash(crypt_salt, password, algorithm) def del_password(name): ''' .. versionadded:: 2015.8.8 Delete the password from name user CLI Example: .. code-block:: bash salt '*' shadow.del_password username ''' cmd = 'passwd -d {0}'.format(name) __salt__['cmd.run'](cmd, python_shell=False, output_loglevel='quiet') uinfo = info(name) return not uinfo['passwd'] def set_warndays(name, warndays): ''' Set the number of days of warning before a password change is required. See man passwd. CLI Example: .. code-block:: bash salt '*' shadow.set_warndays username 7 ''' pre_info = info(name) if warndays == pre_info['warn']: return True cmd = 'passwd -w {0} {1}'.format(warndays, name) __salt__['cmd.run'](cmd, python_shell=False) post_info = info(name) if post_info['warn'] != pre_info['warn']: return post_info['warn'] == warndays return False
saltstack/salt
salt/modules/solaris_shadow.py
set_warndays
python
def set_warndays(name, warndays): ''' Set the number of days of warning before a password change is required. See man passwd. CLI Example: .. code-block:: bash salt '*' shadow.set_warndays username 7 ''' pre_info = info(name) if warndays == pre_info['warn']: return True cmd = 'passwd -w {0} {1}'.format(warndays, name) __salt__['cmd.run'](cmd, python_shell=False) post_info = info(name) if post_info['warn'] != pre_info['warn']: return post_info['warn'] == warndays return False
Set the number of days of warning before a password change is required. See man passwd. CLI Example: .. code-block:: bash salt '*' shadow.set_warndays username 7
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/solaris_shadow.py#L299-L318
[ "def info(name):\n '''\n Return information for the specified user\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' shadow.info root\n '''\n if HAS_SPWD:\n try:\n data = spwd.getspnam(name)\n ret = {\n 'name': data.sp_nam,\n 'passwd': data.sp_pwd,\n 'lstchg': data.sp_lstchg,\n 'min': data.sp_min,\n 'max': data.sp_max,\n 'warn': data.sp_warn,\n 'inact': data.sp_inact,\n 'expire': data.sp_expire}\n except KeyError:\n ret = {\n 'name': '',\n 'passwd': '',\n 'lstchg': '',\n 'min': '',\n 'max': '',\n 'warn': '',\n 'inact': '',\n 'expire': ''}\n return ret\n\n # SmartOS joyent_20130322T181205Z does not have spwd, but not all is lost\n # Return what we can know\n ret = {\n 'name': '',\n 'passwd': '',\n 'lstchg': '',\n 'min': '',\n 'max': '',\n 'warn': '',\n 'inact': '',\n 'expire': ''}\n\n try:\n data = pwd.getpwnam(name)\n ret.update({\n 'name': name\n })\n except KeyError:\n return ret\n\n # To compensate for lack of spwd module, read in password hash from /etc/shadow\n s_file = '/etc/shadow'\n if not os.path.isfile(s_file):\n return ret\n with salt.utils.files.fopen(s_file, 'rb') as ifile:\n for line in ifile:\n comps = line.strip().split(':')\n if comps[0] == name:\n ret.update({'passwd': comps[1]})\n\n # For SmartOS `passwd -s <username>` and the output format is:\n # name status mm/dd/yy min max warn\n #\n # Fields:\n # 1. Name: username\n # 2. Status:\n # - LK: locked\n # - NL: no login\n # - NP: No password\n # - PS: Password\n # 3. Last password change\n # 4. Minimum age\n # 5. Maximum age\n # 6. Warning period\n\n output = __salt__['cmd.run_all']('passwd -s {0}'.format(name), python_shell=False)\n if output['retcode'] != 0:\n return ret\n\n fields = output['stdout'].split()\n if len(fields) == 2:\n # For example:\n # root NL\n return ret\n # We have all fields:\n # buildbot L 05/09/2013 0 99999 7\n ret.update({\n 'name': data.pw_name,\n 'lstchg': fields[2],\n 'min': int(fields[3]),\n 'max': int(fields[4]),\n 'warn': int(fields[5]),\n 'inact': '',\n 'expire': ''\n })\n return ret\n" ]
# -*- coding: utf-8 -*- ''' Manage the password database on Solaris systems .. important:: If you feel that Salt should be using this module to manage passwords on a minion, and it is using a different module (or gives an error similar to *'shadow.info' is not available*), see :ref:`here <module-provider-override>`. ''' from __future__ import absolute_import, unicode_literals, print_function # Import python libs import os try: import spwd HAS_SPWD = True except ImportError: # SmartOS joyent_20130322T181205Z does not have spwd HAS_SPWD = False try: import pwd except ImportError: pass # We're most likely on a Windows machine. # Import salt libs import salt.utils.files from salt.exceptions import CommandExecutionError try: import salt.utils.pycrypto HAS_CRYPT = True except ImportError: HAS_CRYPT = False # Define the module's virtual name __virtualname__ = 'shadow' def __virtual__(): ''' Only work on POSIX-like systems ''' if __grains__.get('kernel', '') == 'SunOS': return __virtualname__ return (False, 'The solaris_shadow execution module failed to load: only available on Solaris systems.') def default_hash(): ''' Returns the default hash used for unset passwords CLI Example: .. code-block:: bash salt '*' shadow.default_hash ''' return '!' def info(name): ''' Return information for the specified user CLI Example: .. code-block:: bash salt '*' shadow.info root ''' if HAS_SPWD: try: data = spwd.getspnam(name) ret = { 'name': data.sp_nam, 'passwd': data.sp_pwd, 'lstchg': data.sp_lstchg, 'min': data.sp_min, 'max': data.sp_max, 'warn': data.sp_warn, 'inact': data.sp_inact, 'expire': data.sp_expire} except KeyError: ret = { 'name': '', 'passwd': '', 'lstchg': '', 'min': '', 'max': '', 'warn': '', 'inact': '', 'expire': ''} return ret # SmartOS joyent_20130322T181205Z does not have spwd, but not all is lost # Return what we can know ret = { 'name': '', 'passwd': '', 'lstchg': '', 'min': '', 'max': '', 'warn': '', 'inact': '', 'expire': ''} try: data = pwd.getpwnam(name) ret.update({ 'name': name }) except KeyError: return ret # To compensate for lack of spwd module, read in password hash from /etc/shadow s_file = '/etc/shadow' if not os.path.isfile(s_file): return ret with salt.utils.files.fopen(s_file, 'rb') as ifile: for line in ifile: comps = line.strip().split(':') if comps[0] == name: ret.update({'passwd': comps[1]}) # For SmartOS `passwd -s <username>` and the output format is: # name status mm/dd/yy min max warn # # Fields: # 1. Name: username # 2. Status: # - LK: locked # - NL: no login # - NP: No password # - PS: Password # 3. Last password change # 4. Minimum age # 5. Maximum age # 6. Warning period output = __salt__['cmd.run_all']('passwd -s {0}'.format(name), python_shell=False) if output['retcode'] != 0: return ret fields = output['stdout'].split() if len(fields) == 2: # For example: # root NL return ret # We have all fields: # buildbot L 05/09/2013 0 99999 7 ret.update({ 'name': data.pw_name, 'lstchg': fields[2], 'min': int(fields[3]), 'max': int(fields[4]), 'warn': int(fields[5]), 'inact': '', 'expire': '' }) return ret def set_maxdays(name, maxdays): ''' Set the maximum number of days during which a password is valid. See man passwd. CLI Example: .. code-block:: bash salt '*' shadow.set_maxdays username 90 ''' pre_info = info(name) if maxdays == pre_info['max']: return True cmd = 'passwd -x {0} {1}'.format(maxdays, name) __salt__['cmd.run'](cmd, python_shell=False) post_info = info(name) if post_info['max'] != pre_info['max']: return post_info['max'] == maxdays def set_mindays(name, mindays): ''' Set the minimum number of days between password changes. See man passwd. CLI Example: .. code-block:: bash salt '*' shadow.set_mindays username 7 ''' pre_info = info(name) if mindays == pre_info['min']: return True cmd = 'passwd -n {0} {1}'.format(mindays, name) __salt__['cmd.run'](cmd, python_shell=False) post_info = info(name) if post_info['min'] != pre_info['min']: return post_info['min'] == mindays return False def gen_password(password, crypt_salt=None, algorithm='sha512'): ''' .. versionadded:: 2015.8.8 Generate hashed password .. note:: When called this function is called directly via remote-execution, the password argument may be displayed in the system's process list. This may be a security risk on certain systems. password Plaintext password to be hashed. crypt_salt Crpytographic salt. If not given, a random 8-character salt will be generated. algorithm The following hash algorithms are supported: * md5 * blowfish (not in mainline glibc, only available in distros that add it) * sha256 * sha512 (default) CLI Example: .. code-block:: bash salt '*' shadow.gen_password 'I_am_password' salt '*' shadow.gen_password 'I_am_password' crypt_salt='I_am_salt' algorithm=sha256 ''' if not HAS_CRYPT: raise CommandExecutionError( 'gen_password is not available on this operating system ' 'because the "crypt" python module is not available.' ) return salt.utils.pycrypto.gen_hash(crypt_salt, password, algorithm) def del_password(name): ''' .. versionadded:: 2015.8.8 Delete the password from name user CLI Example: .. code-block:: bash salt '*' shadow.del_password username ''' cmd = 'passwd -d {0}'.format(name) __salt__['cmd.run'](cmd, python_shell=False, output_loglevel='quiet') uinfo = info(name) return not uinfo['passwd'] def set_password(name, password): ''' Set the password for a named user. The password must be a properly defined hash, the password hash can be generated with this command: ``openssl passwd -1 <plaintext password>`` CLI Example: .. code-block:: bash salt '*' shadow.set_password root $1$UYCIxa628.9qXjpQCjM4a.. ''' s_file = '/etc/shadow' ret = {} if not os.path.isfile(s_file): return ret lines = [] with salt.utils.files.fopen(s_file, 'rb') as ifile: for line in ifile: comps = line.strip().split(':') if comps[0] != name: lines.append(line) continue comps[1] = password line = ':'.join(comps) lines.append('{0}\n'.format(line)) with salt.utils.files.fopen(s_file, 'w+') as ofile: lines = [salt.utils.stringutils.to_str(_l) for _l in lines] ofile.writelines(lines) uinfo = info(name) return uinfo['passwd'] == password
saltstack/salt
salt/pillar/git_pillar.py
ext_pillar
python
def ext_pillar(minion_id, pillar, *repos): # pylint: disable=unused-argument ''' Checkout the ext_pillar sources and compile the resulting pillar SLS ''' opts = copy.deepcopy(__opts__) opts['pillar_roots'] = {} opts['__git_pillar'] = True git_pillar = salt.utils.gitfs.GitPillar( opts, repos, per_remote_overrides=PER_REMOTE_OVERRIDES, per_remote_only=PER_REMOTE_ONLY, global_only=GLOBAL_ONLY) if __opts__.get('__role') == 'minion': # If masterless, fetch the remotes. We'll need to remove this once # we make the minion daemon able to run standalone. git_pillar.fetch_remotes() git_pillar.checkout() ret = {} merge_strategy = __opts__.get( 'pillar_source_merging_strategy', 'smart' ) merge_lists = __opts__.get( 'pillar_merge_lists', False ) for pillar_dir, env in six.iteritems(git_pillar.pillar_dirs): # Map env if env == '__env__' before checking the env value if env == '__env__': env = opts.get('pillarenv') \ or opts.get('saltenv') \ or opts.get('git_pillar_base') log.debug('__env__ maps to %s', env) # If pillarenv is set, only grab pillars with that match pillarenv if opts['pillarenv'] and env != opts['pillarenv']: log.debug( 'env \'%s\' for pillar dir \'%s\' does not match ' 'pillarenv \'%s\', skipping', env, pillar_dir, opts['pillarenv'] ) continue if pillar_dir in git_pillar.pillar_linked_dirs: log.debug( 'git_pillar is skipping processing on %s as it is a ' 'mounted repo', pillar_dir ) continue else: log.debug( 'git_pillar is processing pillar SLS from %s for pillar ' 'env \'%s\'', pillar_dir, env ) pillar_roots = [pillar_dir] if __opts__['git_pillar_includes']: # Add the rest of the pillar_dirs in this environment to the # list, excluding the current pillar_dir being processed. This # is because it was already specified above as the first in the # list, so that its top file is sourced from the correct # location and not from another git_pillar remote. pillar_roots.extend( [d for (d, e) in six.iteritems(git_pillar.pillar_dirs) if env == e and d != pillar_dir] ) opts['pillar_roots'] = {env: pillar_roots} local_pillar = Pillar(opts, __grains__, minion_id, env) ret = salt.utils.dictupdate.merge( ret, local_pillar.compile_pillar(ext=False), strategy=merge_strategy, merge_lists=merge_lists ) return ret
Checkout the ext_pillar sources and compile the resulting pillar SLS
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/pillar/git_pillar.py#L401-L478
[ "def iteritems(d, **kw):\n return d.iteritems(**kw)\n", "def merge(obj_a, obj_b, strategy='smart', renderer='yaml', merge_lists=False):\n if strategy == 'smart':\n if renderer.split('|')[-1] == 'yamlex' or renderer.startswith('yamlex_'):\n strategy = 'aggregate'\n else:\n strategy = 'recurse'\n\n if strategy == 'list':\n merged = merge_list(obj_a, obj_b)\n elif strategy == 'recurse':\n merged = merge_recurse(obj_a, obj_b, merge_lists)\n elif strategy == 'aggregate':\n #: level = 1 merge at least root data\n merged = merge_aggregate(obj_a, obj_b)\n elif strategy == 'overwrite':\n merged = merge_overwrite(obj_a, obj_b, merge_lists)\n elif strategy == 'none':\n # If we do not want to merge, there is only one pillar passed, so we can safely use the default recurse,\n # we just do not want to log an error\n merged = merge_recurse(obj_a, obj_b)\n else:\n log.warning(\n 'Unknown merging strategy \\'%s\\', fallback to recurse',\n strategy\n )\n merged = merge_recurse(obj_a, obj_b)\n\n return merged\n", "def compile_pillar(self, ext=True):\n '''\n Render the pillar data and return\n '''\n top, top_errors = self.get_top()\n if ext:\n if self.opts.get('ext_pillar_first', False):\n self.opts['pillar'], errors = self.ext_pillar(self.pillar_override)\n self.rend = salt.loader.render(self.opts, self.functions)\n matches = self.top_matches(top)\n pillar, errors = self.render_pillar(matches, errors=errors)\n pillar = merge(\n self.opts['pillar'],\n pillar,\n self.merge_strategy,\n self.opts.get('renderer', 'yaml'),\n self.opts.get('pillar_merge_lists', False))\n else:\n matches = self.top_matches(top)\n pillar, errors = self.render_pillar(matches)\n pillar, errors = self.ext_pillar(pillar, errors=errors)\n else:\n matches = self.top_matches(top)\n pillar, errors = self.render_pillar(matches)\n errors.extend(top_errors)\n if self.opts.get('pillar_opts', False):\n mopts = dict(self.opts)\n if 'grains' in mopts:\n mopts.pop('grains')\n mopts['saltversion'] = __version__\n pillar['master'] = mopts\n if 'pillar' in self.opts and self.opts.get('ssh_merge_pillar', False):\n pillar = merge(\n self.opts['pillar'],\n pillar,\n self.merge_strategy,\n self.opts.get('renderer', 'yaml'),\n self.opts.get('pillar_merge_lists', False))\n if errors:\n for error in errors:\n log.critical('Pillar render error: %s', error)\n pillar['_errors'] = errors\n\n if self.pillar_override:\n pillar = merge(\n pillar,\n self.pillar_override,\n self.merge_strategy,\n self.opts.get('renderer', 'yaml'),\n self.opts.get('pillar_merge_lists', False))\n\n decrypt_errors = self.decrypt_pillar(pillar)\n if decrypt_errors:\n pillar.setdefault('_errors', []).extend(decrypt_errors)\n\n return pillar\n", "def fetch_remotes(self, remotes=None):\n '''\n Fetch all remotes and return a boolean to let the calling function know\n whether or not any remotes were updated in the process of fetching\n '''\n if remotes is None:\n remotes = []\n elif not isinstance(remotes, list):\n log.error(\n 'Invalid \\'remotes\\' argument (%s) for fetch_remotes. '\n 'Must be a list of strings', remotes\n )\n remotes = []\n\n changed = False\n for repo in self.remotes:\n name = getattr(repo, 'name', None)\n if not remotes or (repo.id, name) in remotes:\n try:\n if repo.fetch():\n # We can't just use the return value from repo.fetch()\n # because the data could still have changed if old\n # remotes were cleared above. Additionally, we're\n # running this in a loop and later remotes without\n # changes would override this value and make it\n # incorrect.\n changed = True\n except Exception as exc:\n log.error(\n 'Exception caught while fetching %s remote \\'%s\\': %s',\n self.role, repo.id, exc,\n exc_info=True\n )\n return changed\n", "def checkout(self):\n '''\n Checkout the targeted branches/tags from the git_pillar remotes\n '''\n self.pillar_dirs = OrderedDict()\n self.pillar_linked_dirs = []\n for repo in self.remotes:\n cachedir = self.do_checkout(repo)\n if cachedir is not None:\n # Figure out which environment this remote should be assigned\n if repo.branch == '__env__' and hasattr(repo, 'all_saltenvs'):\n env = self.opts.get('pillarenv') \\\n or self.opts.get('saltenv') \\\n or self.opts.get('git_pillar_base')\n elif repo.env:\n env = repo.env\n else:\n if repo.branch == repo.base:\n env = 'base'\n else:\n tgt = repo.get_checkout_target()\n env = 'base' if tgt == repo.base else tgt\n if repo._mountpoint:\n if self.link_mountpoint(repo):\n self.pillar_dirs[repo.linkdir] = env\n self.pillar_linked_dirs.append(repo.linkdir)\n else:\n self.pillar_dirs[cachedir] = env\n" ]
# -*- coding: utf-8 -*- ''' Use a git repository as a Pillar source --------------------------------------- This external pillar allows for a Pillar top file and Pillar SLS files to be sourced from a git repository. However, since git_pillar does not have an equivalent to the :conf_master:`pillar_roots` parameter, configuration is slightly different. A Pillar top file is required to be in the git repository and must still contain the relevant environment, like so: .. code-block:: yaml base: '*': - foo The branch/tag which maps to that environment must then be specified along with the repo's URL. Configuration details can be found below. .. important:: Each branch/tag used for git_pillar must have its own top file. This is different from how the top file works when configuring :ref:`States <states-tutorial>`. The reason for this is that each git_pillar branch/tag is processed separately from the rest. Therefore, if the ``qa`` branch is to be used for git_pillar, it would need to have its own top file, with the ``qa`` environment defined within it, like this: .. code-block:: yaml qa: 'dev-*': - bar Additionally, while git_pillar allows for the branch/tag to be overridden (see :ref:`here <git-pillar-env-remap>`), keep in mind that the top file must reference the actual environment name. It is common practice to make the environment in a git_pillar top file match the branch/tag name, but when remapping, the environment of course no longer matches the branch/tag, and the top file needs to be adjusted accordingly. When expected Pillar values configured in git_pillar are missing, this is a common misconfiguration that may be to blame, and is a good first step in troubleshooting. .. _git-pillar-configuration: Configuring git_pillar for Salt =============================== Beginning with Salt version 2015.8.0, pygit2_ is now supported in addition to GitPython_. The requirements for GitPython_ and pygit2_ are the same as for GitFS, as described :ref:`here <gitfs-dependencies>`. .. important:: git_pillar has its own set of global configuration parameters. While it may seem intuitive to use the global gitfs configuration parameters (:conf_master:`gitfs_base`, etc.) to manage git_pillar, this will not work. The main difference for this is the fact that the different components which use Salt's git backend code do not all function identically. For instance, in git_pillar it is necessary to specify which branch/tag to be used for git_pillar remotes. This is the reverse behavior from gitfs, where branches/tags make up your environments. See :ref:`here <git-pillar-config-opts>` for documentation on the git_pillar configuration options and their usage. Here is an example git_pillar configuration: .. code-block:: yaml ext_pillar: - git: # Use 'prod' instead of the branch name 'production' as the environment - production https://gitserver/git-pillar.git: - env: prod # Use 'dev' instead of the branch name 'develop' as the environment - develop https://gitserver/git-pillar.git: - env: dev # No per-remote config parameters (and no trailing colon), 'qa' will # be used as the environment - qa https://gitserver/git-pillar.git # SSH key authentication - master git@other-git-server:pillardata-ssh.git: # Pillar SLS files will be read from the 'pillar' subdirectory in # this repository - root: pillar - privkey: /path/to/key - pubkey: /path/to/key.pub - passphrase: CorrectHorseBatteryStaple # HTTPS authentication - master https://other-git-server/pillardata-https.git: - user: git - password: CorrectHorseBatteryStaple The main difference between this and the old way of configuring git_pillar is that multiple remotes can be configured under one ``git`` section under :conf_master:`ext_pillar`. More than one ``git`` section can be used, but it is not necessary. Remotes will be evaluated sequentially. Per-remote configuration parameters are supported (similar to :ref:`gitfs <gitfs-per-remote-config>`), and global versions of the git_pillar configuration parameters can also be set. .. _git-pillar-env-remap: To remap a specific branch to a specific Pillar environment, use the ``env`` per-remote parameter: .. code-block:: yaml ext_pillar: - git: - production https://gitserver/git-pillar.git: - env: prod If ``__env__`` is specified as the branch name, then git_pillar will decide which branch to use based on the following criteria: - If the minion has a :conf_minion:`pillarenv` configured, it will use that pillar environment. (2016.11.2 and later) - Otherwise, if the minion has an ``environment`` configured, it will use that environment. - Otherwise, the master's :conf_master:`git_pillar_base` will be used. .. note:: The use of :conf_minion:`environment` to choose the pillar environment dates from a time before the :conf_minion:`pillarenv` parameter was added. In a future release, it will be ignored and either the minion's :conf_minion:`pillarenv` or the master's :conf_master:`git_pillar_base` will be used. Here's an example of using ``__env__`` as the git_pillar environment: .. code-block:: yaml ext_pillar: - git: - __env__ https://gitserver/git-pillar.git: - root: pillar The corresponding Pillar top file would look like this: .. code-block:: yaml "{{saltenv}}": '*': - bar With the addition of pygit2_ support, git_pillar can now interact with authenticated remotes. Authentication works just like in gitfs (as outlined in the :ref:`Git Fileserver Backend Walkthrough <gitfs-authentication>`), only with the global authenication parameter names prefixed with ``git_pillar`` instead of ``gitfs`` (e.g. :conf_master:`git_pillar_pubkey`, :conf_master:`git_pillar_privkey`, :conf_master:`git_pillar_passphrase`, etc.). .. note:: The ``name`` parameter can be used to further differentiate between two remotes with the same URL and branch. When using two remotes with the same URL, the ``name`` option is required. .. _GitPython: https://github.com/gitpython-developers/GitPython .. _pygit2: https://github.com/libgit2/pygit2 .. _git-pillar-multiple-remotes: How Multiple Remotes Are Handled ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ As noted above, multiple remotes can be included in the same ``git`` ext_pillar configuration. Consider the following: .. code-block:: yaml my_etcd_config: etcd.host: 127.0.0.1 etcd.port: 4001 ext_pillar: - etcd: my_etcd_config - git: - master https://mydomain.tld/foo.git: - root: pillar - master https://mydomain.tld/bar.git - master https://mydomain.tld/baz.git - dev https://mydomain.tld/qux.git - git: - master https://mydomain.tld/abc.git - dev https://mydomain.tld/123.git To understand how pillar data from these repos will be compiled, it's important to know how Salt will process them. The following points should be kept in mind: 1. Each ext_pillar is called separately from the others. So, in the above example, the :mod:`etcd <salt.pillar.etcd>` ext_pillar will be evaluated first, with the first group of git_pillar remotes evaluated next (and merged into the etcd pillar data). Lastly, the second group of git_pillar remotes will be evaluated, and then merged into the ext_pillar data evaluated before it. 2. Within a single group of git_pillar remotes, each remote will be evaluated in order, with results merged together as each remote is evaluated. .. note:: Prior to the 2017.7.0 release, remotes would be evaluated in a non-deterministic order. 3. By default, when a repo is evaluated, other remotes' which share its pillar environment will have their files made available to the remote being processed. The first point should be straightforward enough, but the second and third could use some additional clarification. First, point #2. In the first group of git_pillar remotes, the top file and pillar SLS files in the ``foo`` remote will be evaluated first. The ``bar`` remote will be evaluated next, and its results will be merged into the pillar data compiled when the ``foo`` remote was evaluated. As the subsequent remotes are evaluated, their data will be merged in the same fashion. But wait, don't these repositories belong to more than one pillar environments? Well, yes. The default method of generating pillar data compiles pillar data from all environments. This behavior can be overridden using a ``pillarenv``. Setting a :conf_minion:`pillarenv` in the minion config file will make that minion tell the master to ignore any pillar data from environments which don't match that pillarenv. A pillarenv can also be specified for a given minion or set of minions when :mod:`running states <salt.modules.state>`, by using he ``pillarenv`` argument. The CLI pillarenv will override one set in the minion config file. So, assuming that a pillarenv of ``base`` was set for a minion, it would not get any of the pillar variables configured in the ``qux`` remote, since that remote is assigned to the ``dev`` environment. The only way to get its pillar data would be to specify a pillarenv of ``dev``, which would mean that it would then ignore any items from the ``base`` pillarenv. A more detailed explanation of pillar environments can be found :ref:`here <pillar-environments>`. Moving on to point #3, and looking at the example ext_pillar configuration, as the ``foo`` remote is evaluated, it will also have access to the files from the ``bar`` and ``baz`` remotes, since all three are assigned to the ``base`` pillar environment. So, if an SLS file referenced by the ``foo`` remotes's top file does not exist in the ``foo`` remote, it will be searched for in the ``bar`` remote, followed by the ``baz`` remote. When it comes time to evaluate the ``bar`` remote, SLS files referenced by the ``bar`` remote's top file will first be looked for in the ``bar`` remote, followed by ``foo``, and ``baz``, and when the ``baz`` remote is processed, SLS files will be looked for in ``baz``, followed by ``foo`` and ``bar``. This "failover" logic is called a :ref:`directory overlay <file-roots-directory-overlay>`, and it is also used by :conf_master:`file_roots` and :conf_minion`pillar_roots`. The ordering of which remote is checked for SLS files is determined by the order they are listed. First the remote being processed is checked, then the others that share the same environment are checked. However, before the 2017.7.0 release, since evaluation was unordered, the remote being processed would be checked, followed in no specific order by the other repos which share the same environment. Beginning with the 2017.7.0 release, this behavior of git_pillar remotes having access to files in other repos which share the same environment can be disabled by setting :conf_master:`git_pillar_includes` to ``False``. If this is done, then all git_pillar remotes will only have access to their own SLS files. Another way of ensuring that a git_pillar remote will not have access to SLS files from other git_pillar remotes which share the same pillar environment is to put them in a separate ``git`` section under ``ext_pillar``. Look again at the example configuration above. In the second group of git_pillar remotes, the ``abc`` remote would not have access to the SLS files from the ``foo``, ``bar``, and ``baz`` remotes, and vice-versa. .. _git-pillar-mountpoints: Mountpoints ~~~~~~~~~~~ .. versionadded:: 2017.7.0 Assume the following pillar top file: .. code-block:: yaml base: 'web*': - common - web.server.nginx - web.server.appdata Now, assume that you would like to configure the ``web.server.nginx`` and ``web.server.appdata`` SLS files in separate repos. This could be done using the following ext_pillar configuration (assuming that :conf_master:`git_pillar_includes` has not been set to ``False``): .. code-block:: yaml ext_pillar: - git: - master https://mydomain.tld/pillar-common.git - master https://mydomain.tld/pillar-nginx.git - master https://mydomain.tld/pillar-appdata.git However, in order to get the files in the second and third git_pillar remotes to work, you would need to first create the directory structure underneath it (i.e. place them underneath ``web/server/`` in the repository). This also makes it tedious to reorganize the configuration, as changing ``web.server.nginx`` to ``web.nginx`` in the top file would require you to also move the SLS files in the ``pillar-nginx`` up a directory level. For these reasons, much like gitfs, git_pillar now supports a "mountpoint" feature. Using the following ext_pillar configuration, the SLS files in the second and third git_pillar remotes can be placed in the root of the git repository: .. code-block:: yaml ext_pillar: - git: - master https://mydomain.tld/pillar-common.git - master https://mydomain.tld/pillar-nginx.git: - mountpoint: web/server/ - master https://mydomain.tld/pillar-appdata.git: - mountpoint: web/server/ Now, if the top file changed the SLS target from ``web.server.nginx``, instead of reorganizing the git repository, you would just need to adjust the mountpoint to ``web/`` (and restart the ``salt-master`` daemon). .. note:: - Leading and trailing slashes on the mountpoints are optional. - Use of the ``mountpoint`` feature requires that :conf_master:`git_pillar_includes` is not disabled. - Content from mounted git_pillar repos can only be referenced by a top file in the same pillar environment. - Salt versions prior to 2018.3.4 ignore the ``root`` parameter when ``mountpoint`` is set. .. _git-pillar-all_saltenvs: all_saltenvs ~~~~~~~~~~~~ .. versionadded:: 2018.3.4 When ``__env__`` is specified as the branch name, ``all_saltenvs`` per-remote configuration parameter overrides the logic Salt uses to map branches/tags to pillar environments (i.e. pillarenvs). This allows a single branch/tag to appear in all saltenvs. Example: .. code-block:: yaml ext_pillar: - git: - __env__ https://mydomain.tld/top.git - all_saltenvs: master - __env__ https://mydomain.tld/pillar-nginx.git: - mountpoint: web/server/ - __env__ https://mydomain.tld/pillar-appdata.git: - mountpoint: web/server/ ''' from __future__ import absolute_import, print_function, unicode_literals # Import python libs import copy import logging # Import salt libs import salt.utils.gitfs import salt.utils.dictupdate import salt.utils.stringutils import salt.utils.versions from salt.exceptions import FileserverConfigError from salt.pillar import Pillar # Import third party libs from salt.ext import six PER_REMOTE_OVERRIDES = ('base', 'env', 'root', 'ssl_verify', 'refspecs') PER_REMOTE_ONLY = ('name', 'mountpoint', 'all_saltenvs') GLOBAL_ONLY = ('branch',) # Set up logging log = logging.getLogger(__name__) # Define the module's virtual name __virtualname__ = 'git' def __virtual__(): ''' Only load if gitpython is available ''' git_ext_pillars = [x for x in __opts__['ext_pillar'] if 'git' in x] if not git_ext_pillars: # No git external pillars were configured return False try: salt.utils.gitfs.GitPillar(__opts__, init_remotes=False) # Initialization of the GitPillar object did not fail, so we # know we have valid configuration syntax and that a valid # provider was detected. return __virtualname__ except FileserverConfigError: return False def _extract_key_val(kv, delimiter='='): '''Extract key and value from key=val string. Example: >>> _extract_key_val('foo=bar') ('foo', 'bar') ''' pieces = kv.split(delimiter) key = pieces[0] val = delimiter.join(pieces[1:]) return key, val
saltstack/salt
salt/modules/mac_system.py
_execute_command
python
def _execute_command(cmd, at_time=None): ''' Helper function to execute the command :param str cmd: the command to run :param str at_time: If passed, the cmd will be scheduled. Returns: bool ''' if at_time: cmd = 'echo \'{0}\' | at {1}'.format(cmd, _cmd_quote(at_time)) return not bool(__salt__['cmd.retcode'](cmd, python_shell=True))
Helper function to execute the command :param str cmd: the command to run :param str at_time: If passed, the cmd will be scheduled. Returns: bool
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/mac_system.py#L68-L80
null
# -*- coding: utf-8 -*- ''' System module for sleeping, restarting, and shutting down the system on Mac OS X .. versionadded:: 2016.3.0 .. warning:: Using this module will enable ``atrun`` on the system if it is disabled. ''' from __future__ import absolute_import, unicode_literals, print_function # Import python libs try: # python 3 from shlex import quote as _cmd_quote # pylint: disable=E0611 except ImportError: # python 2 from pipes import quote as _cmd_quote import getpass # Import salt libs import salt.utils.platform from salt.exceptions import SaltInvocationError, CommandExecutionError __virtualname__ = 'system' def __virtual__(): ''' Only for MacOS with atrun enabled ''' if not salt.utils.platform.is_darwin(): return (False, 'The mac_system module could not be loaded: ' 'module only works on MacOS systems.') if getpass.getuser() != 'root': return False, 'The mac_system module is not useful for non-root users.' if not _atrun_enabled(): if not _enable_atrun(): return False, 'atrun could not be enabled on this system' return __virtualname__ def _atrun_enabled(): ''' Check to see if atrun is running and enabled on the system ''' try: return __salt__['service.list']('com.apple.atrun') except CommandExecutionError: return False def _enable_atrun(): ''' Enable and start the atrun daemon ''' name = 'com.apple.atrun' try: __salt__['service.enable'](name) __salt__['service.start'](name) except CommandExecutionError: return False return _atrun_enabled() def halt(at_time=None): ''' Halt a running system :param str at_time: Any valid `at` expression. For example, some valid at expressions could be: - noon - midnight - fri - 9:00 AM - 2:30 PM tomorrow - now + 10 minutes .. note:: If you pass a time only, with no 'AM/PM' designation, you have to double quote the parameter on the command line. For example: '"14:00"' CLI Example: .. code-block:: bash salt '*' system.halt salt '*' system.halt 'now + 10 minutes' ''' cmd = 'shutdown -h now' return _execute_command(cmd, at_time) def sleep(at_time=None): ''' Sleep the system. If a user is active on the system it will likely fail to sleep. :param str at_time: Any valid `at` expression. For example, some valid at expressions could be: - noon - midnight - fri - 9:00 AM - 2:30 PM tomorrow - now + 10 minutes .. note:: If you pass a time only, with no 'AM/PM' designation, you have to double quote the parameter on the command line. For example: '"14:00"' CLI Example: .. code-block:: bash salt '*' system.sleep salt '*' system.sleep '10:00 PM' ''' cmd = 'shutdown -s now' return _execute_command(cmd, at_time) def restart(at_time=None): ''' Restart the system :param str at_time: Any valid `at` expression. For example, some valid at expressions could be: - noon - midnight - fri - 9:00 AM - 2:30 PM tomorrow - now + 10 minutes .. note:: If you pass a time only, with no 'AM/PM' designation, you have to double quote the parameter on the command line. For example: '"14:00"' CLI Example: .. code-block:: bash salt '*' system.restart salt '*' system.restart '12:00 PM fri' ''' cmd = 'shutdown -r now' return _execute_command(cmd, at_time) def shutdown(at_time=None): ''' Shutdown the system :param str at_time: Any valid `at` expression. For example, some valid at expressions could be: - noon - midnight - fri - 9:00 AM - 2:30 PM tomorrow - now + 10 minutes .. note:: If you pass a time only, with no 'AM/PM' designation, you have to double quote the parameter on the command line. For example: '"14:00"' CLI Example: .. code-block:: bash salt '*' system.shutdown salt '*' system.shutdown 'now + 1 hour' ''' return halt(at_time) def get_remote_login(): ''' Displays whether remote login (SSH) is on or off. :return: True if remote login is on, False if off :rtype: bool CLI Example: .. code-block:: bash salt '*' system.get_remote_login ''' ret = __utils__['mac_utils.execute_return_result']( 'systemsetup -getremotelogin') enabled = __utils__['mac_utils.validate_enabled']( __utils__['mac_utils.parse_return'](ret)) return enabled == 'on' def set_remote_login(enable): ''' Set the remote login (SSH) to either on or off. :param bool enable: True to enable, False to disable. "On" and "Off" are also acceptable values. Additionally you can pass 1 and 0 to represent True and False respectively :return: True if successful, False if not :rtype: bool CLI Example: .. code-block:: bash salt '*' system.set_remote_login True ''' state = __utils__['mac_utils.validate_enabled'](enable) cmd = 'systemsetup -f -setremotelogin {0}'.format(state) __utils__['mac_utils.execute_return_success'](cmd) return __utils__['mac_utils.confirm_updated'](state, get_remote_login, normalize_ret=True) def get_remote_events(): ''' Displays whether remote apple events are on or off. :return: True if remote apple events are on, False if off :rtype: bool CLI Example: .. code-block:: bash salt '*' system.get_remote_events ''' ret = __utils__['mac_utils.execute_return_result']( 'systemsetup -getremoteappleevents') enabled = __utils__['mac_utils.validate_enabled']( __utils__['mac_utils.parse_return'](ret)) return enabled == 'on' def set_remote_events(enable): ''' Set whether the server responds to events sent by other computers (such as AppleScripts) :param bool enable: True to enable, False to disable. "On" and "Off" are also acceptable values. Additionally you can pass 1 and 0 to represent True and False respectively :return: True if successful, False if not :rtype: bool CLI Example: .. code-block:: bash salt '*' system.set_remote_events On ''' state = __utils__['mac_utils.validate_enabled'](enable) cmd = 'systemsetup -setremoteappleevents {0}'.format(state) __utils__['mac_utils.execute_return_success'](cmd) return __utils__['mac_utils.confirm_updated']( state, get_remote_events, normalize_ret=True, ) def get_computer_name(): ''' Gets the computer name :return: The computer name :rtype: str CLI Example: .. code-block:: bash salt '*' system.get_computer_name ''' ret = __utils__['mac_utils.execute_return_result']( 'systemsetup -getcomputername') return __utils__['mac_utils.parse_return'](ret) def set_computer_name(name): ''' Set the computer name :param str name: The new computer name :return: True if successful, False if not :rtype: bool CLI Example: .. code-block:: bash salt '*' system.set_computer_name "Mike's Mac" ''' cmd = 'systemsetup -setcomputername "{0}"'.format(name) __utils__['mac_utils.execute_return_success'](cmd) return __utils__['mac_utils.confirm_updated']( name, get_computer_name, ) def get_subnet_name(): ''' Gets the local subnet name :return: The local subnet name :rtype: str CLI Example: .. code-block:: bash salt '*' system.get_subnet_name ''' ret = __utils__['mac_utils.execute_return_result']( 'systemsetup -getlocalsubnetname') return __utils__['mac_utils.parse_return'](ret) def set_subnet_name(name): ''' Set the local subnet name :param str name: The new local subnet name .. note:: Spaces are changed to dashes. Other special characters are removed. :return: True if successful, False if not :rtype: bool CLI Example: .. code-block:: bash The following will be set as 'Mikes-Mac' salt '*' system.set_subnet_name "Mike's Mac" ''' cmd = 'systemsetup -setlocalsubnetname "{0}"'.format(name) __utils__['mac_utils.execute_return_success'](cmd) return __utils__['mac_utils.confirm_updated']( name, get_subnet_name, ) def get_startup_disk(): ''' Displays the current startup disk :return: The current startup disk :rtype: str CLI Example: .. code-block:: bash salt '*' system.get_startup_disk ''' ret = __utils__['mac_utils.execute_return_result']( 'systemsetup -getstartupdisk') return __utils__['mac_utils.parse_return'](ret) def list_startup_disks(): ''' List all valid startup disks on the system. :return: A list of valid startup disks :rtype: list CLI Example: .. code-block:: bash salt '*' system.list_startup_disks ''' ret = __utils__['mac_utils.execute_return_result']( 'systemsetup -liststartupdisks') return ret.splitlines() def set_startup_disk(path): ''' Set the current startup disk to the indicated path. Use ``system.list_startup_disks`` to find valid startup disks on the system. :param str path: The valid startup disk path :return: True if successful, False if not :rtype: bool CLI Example: .. code-block:: bash salt '*' system.set_startup_disk /System/Library/CoreServices ''' if path not in list_startup_disks(): msg = 'Invalid value passed for path.\n' \ 'Must be a valid startup disk as found in ' \ 'system.list_startup_disks.\n' \ 'Passed: {0}'.format(path) raise SaltInvocationError(msg) cmd = 'systemsetup -setstartupdisk {0}'.format(path) __utils__['mac_utils.execute_return_result'](cmd) return __utils__['mac_utils.confirm_updated']( path, get_startup_disk, ) def get_restart_delay(): ''' Get the number of seconds after which the computer will start up after a power failure. :return: A string value representing the number of seconds the system will delay restart after power loss :rtype: str CLI Example: .. code-block:: bash salt '*' system.get_restart_delay ''' ret = __utils__['mac_utils.execute_return_result']( 'systemsetup -getwaitforstartupafterpowerfailure') return __utils__['mac_utils.parse_return'](ret) def set_restart_delay(seconds): ''' Set the number of seconds after which the computer will start up after a power failure. .. warning:: This command fails with the following error: ``Error, IOServiceOpen returned 0x10000003`` The setting is not updated. This is an apple bug. It seems like it may only work on certain versions of Mac Server X. This article explains the issue in more detail, though it is quite old. http://lists.apple.com/archives/macos-x-server/2006/Jul/msg00967.html :param int seconds: The number of seconds. Must be a multiple of 30 :return: True if successful, False if not :rtype: bool CLI Example: .. code-block:: bash salt '*' system.set_restart_delay 180 ''' if seconds % 30 != 0: msg = 'Invalid value passed for seconds.\n' \ 'Must be a multiple of 30.\n' \ 'Passed: {0}'.format(seconds) raise SaltInvocationError(msg) cmd = 'systemsetup -setwaitforstartupafterpowerfailure {0}'.format(seconds) __utils__['mac_utils.execute_return_success'](cmd) return __utils__['mac_utils.confirm_updated']( seconds, get_restart_delay, ) def get_disable_keyboard_on_lock(): ''' Get whether or not the keyboard should be disabled when the X Serve enclosure lock is engaged. :return: True if disable keyboard on lock is on, False if off :rtype: bool CLI Example: ..code-block:: bash salt '*' system.get_disable_keyboard_on_lock ''' ret = __utils__['mac_utils.execute_return_result']( 'systemsetup -getdisablekeyboardwhenenclosurelockisengaged') enabled = __utils__['mac_utils.validate_enabled']( __utils__['mac_utils.parse_return'](ret)) return enabled == 'on' def set_disable_keyboard_on_lock(enable): ''' Get whether or not the keyboard should be disabled when the X Serve enclosure lock is engaged. :param bool enable: True to enable, False to disable. "On" and "Off" are also acceptable values. Additionally you can pass 1 and 0 to represent True and False respectively :return: True if successful, False if not :rtype: bool CLI Example: .. code-block:: bash salt '*' system.set_disable_keyboard_on_lock False ''' state = __utils__['mac_utils.validate_enabled'](enable) cmd = 'systemsetup -setdisablekeyboardwhenenclosurelockisengaged ' \ '{0}'.format(state) __utils__['mac_utils.execute_return_success'](cmd) return __utils__['mac_utils.confirm_updated']( state, get_disable_keyboard_on_lock, normalize_ret=True, ) def get_boot_arch(): ''' Get the kernel architecture setting from ``com.apple.Boot.plist`` :return: A string value representing the boot architecture setting :rtype: str CLI Example: .. code-block:: bash salt '*' system.get_boot_arch ''' ret = __utils__['mac_utils.execute_return_result']( 'systemsetup -getkernelbootarchitecturesetting') arch = __utils__['mac_utils.parse_return'](ret) if 'default' in arch: return 'default' elif 'i386' in arch: return 'i386' elif 'x86_64' in arch: return 'x86_64' return 'unknown' def set_boot_arch(arch='default'): ''' Set the kernel to boot in 32 or 64 bit mode on next boot. .. note:: When this function fails with the error ``changes to kernel architecture failed to save!``, then the boot arch is not updated. This is either an Apple bug, not available on the test system, or a result of system files being locked down in macOS (SIP Protection). :param str arch: A string representing the desired architecture. If no value is passed, default is assumed. Valid values include: - i386 - x86_64 - default :return: True if successful, False if not :rtype: bool CLI Example: .. code-block:: bash salt '*' system.set_boot_arch i386 ''' if arch not in ['i386', 'x86_64', 'default']: msg = 'Invalid value passed for arch.\n' \ 'Must be i386, x86_64, or default.\n' \ 'Passed: {0}'.format(arch) raise SaltInvocationError(msg) cmd = 'systemsetup -setkernelbootarchitecture {0}'.format(arch) __utils__['mac_utils.execute_return_success'](cmd) return __utils__['mac_utils.confirm_updated']( arch, get_boot_arch, )
saltstack/salt
salt/modules/mac_system.py
set_remote_login
python
def set_remote_login(enable): ''' Set the remote login (SSH) to either on or off. :param bool enable: True to enable, False to disable. "On" and "Off" are also acceptable values. Additionally you can pass 1 and 0 to represent True and False respectively :return: True if successful, False if not :rtype: bool CLI Example: .. code-block:: bash salt '*' system.set_remote_login True ''' state = __utils__['mac_utils.validate_enabled'](enable) cmd = 'systemsetup -f -setremotelogin {0}'.format(state) __utils__['mac_utils.execute_return_success'](cmd) return __utils__['mac_utils.confirm_updated'](state, get_remote_login, normalize_ret=True)
Set the remote login (SSH) to either on or off. :param bool enable: True to enable, False to disable. "On" and "Off" are also acceptable values. Additionally you can pass 1 and 0 to represent True and False respectively :return: True if successful, False if not :rtype: bool CLI Example: .. code-block:: bash salt '*' system.set_remote_login True
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/mac_system.py#L221-L245
null
# -*- coding: utf-8 -*- ''' System module for sleeping, restarting, and shutting down the system on Mac OS X .. versionadded:: 2016.3.0 .. warning:: Using this module will enable ``atrun`` on the system if it is disabled. ''' from __future__ import absolute_import, unicode_literals, print_function # Import python libs try: # python 3 from shlex import quote as _cmd_quote # pylint: disable=E0611 except ImportError: # python 2 from pipes import quote as _cmd_quote import getpass # Import salt libs import salt.utils.platform from salt.exceptions import SaltInvocationError, CommandExecutionError __virtualname__ = 'system' def __virtual__(): ''' Only for MacOS with atrun enabled ''' if not salt.utils.platform.is_darwin(): return (False, 'The mac_system module could not be loaded: ' 'module only works on MacOS systems.') if getpass.getuser() != 'root': return False, 'The mac_system module is not useful for non-root users.' if not _atrun_enabled(): if not _enable_atrun(): return False, 'atrun could not be enabled on this system' return __virtualname__ def _atrun_enabled(): ''' Check to see if atrun is running and enabled on the system ''' try: return __salt__['service.list']('com.apple.atrun') except CommandExecutionError: return False def _enable_atrun(): ''' Enable and start the atrun daemon ''' name = 'com.apple.atrun' try: __salt__['service.enable'](name) __salt__['service.start'](name) except CommandExecutionError: return False return _atrun_enabled() def _execute_command(cmd, at_time=None): ''' Helper function to execute the command :param str cmd: the command to run :param str at_time: If passed, the cmd will be scheduled. Returns: bool ''' if at_time: cmd = 'echo \'{0}\' | at {1}'.format(cmd, _cmd_quote(at_time)) return not bool(__salt__['cmd.retcode'](cmd, python_shell=True)) def halt(at_time=None): ''' Halt a running system :param str at_time: Any valid `at` expression. For example, some valid at expressions could be: - noon - midnight - fri - 9:00 AM - 2:30 PM tomorrow - now + 10 minutes .. note:: If you pass a time only, with no 'AM/PM' designation, you have to double quote the parameter on the command line. For example: '"14:00"' CLI Example: .. code-block:: bash salt '*' system.halt salt '*' system.halt 'now + 10 minutes' ''' cmd = 'shutdown -h now' return _execute_command(cmd, at_time) def sleep(at_time=None): ''' Sleep the system. If a user is active on the system it will likely fail to sleep. :param str at_time: Any valid `at` expression. For example, some valid at expressions could be: - noon - midnight - fri - 9:00 AM - 2:30 PM tomorrow - now + 10 minutes .. note:: If you pass a time only, with no 'AM/PM' designation, you have to double quote the parameter on the command line. For example: '"14:00"' CLI Example: .. code-block:: bash salt '*' system.sleep salt '*' system.sleep '10:00 PM' ''' cmd = 'shutdown -s now' return _execute_command(cmd, at_time) def restart(at_time=None): ''' Restart the system :param str at_time: Any valid `at` expression. For example, some valid at expressions could be: - noon - midnight - fri - 9:00 AM - 2:30 PM tomorrow - now + 10 minutes .. note:: If you pass a time only, with no 'AM/PM' designation, you have to double quote the parameter on the command line. For example: '"14:00"' CLI Example: .. code-block:: bash salt '*' system.restart salt '*' system.restart '12:00 PM fri' ''' cmd = 'shutdown -r now' return _execute_command(cmd, at_time) def shutdown(at_time=None): ''' Shutdown the system :param str at_time: Any valid `at` expression. For example, some valid at expressions could be: - noon - midnight - fri - 9:00 AM - 2:30 PM tomorrow - now + 10 minutes .. note:: If you pass a time only, with no 'AM/PM' designation, you have to double quote the parameter on the command line. For example: '"14:00"' CLI Example: .. code-block:: bash salt '*' system.shutdown salt '*' system.shutdown 'now + 1 hour' ''' return halt(at_time) def get_remote_login(): ''' Displays whether remote login (SSH) is on or off. :return: True if remote login is on, False if off :rtype: bool CLI Example: .. code-block:: bash salt '*' system.get_remote_login ''' ret = __utils__['mac_utils.execute_return_result']( 'systemsetup -getremotelogin') enabled = __utils__['mac_utils.validate_enabled']( __utils__['mac_utils.parse_return'](ret)) return enabled == 'on' def get_remote_events(): ''' Displays whether remote apple events are on or off. :return: True if remote apple events are on, False if off :rtype: bool CLI Example: .. code-block:: bash salt '*' system.get_remote_events ''' ret = __utils__['mac_utils.execute_return_result']( 'systemsetup -getremoteappleevents') enabled = __utils__['mac_utils.validate_enabled']( __utils__['mac_utils.parse_return'](ret)) return enabled == 'on' def set_remote_events(enable): ''' Set whether the server responds to events sent by other computers (such as AppleScripts) :param bool enable: True to enable, False to disable. "On" and "Off" are also acceptable values. Additionally you can pass 1 and 0 to represent True and False respectively :return: True if successful, False if not :rtype: bool CLI Example: .. code-block:: bash salt '*' system.set_remote_events On ''' state = __utils__['mac_utils.validate_enabled'](enable) cmd = 'systemsetup -setremoteappleevents {0}'.format(state) __utils__['mac_utils.execute_return_success'](cmd) return __utils__['mac_utils.confirm_updated']( state, get_remote_events, normalize_ret=True, ) def get_computer_name(): ''' Gets the computer name :return: The computer name :rtype: str CLI Example: .. code-block:: bash salt '*' system.get_computer_name ''' ret = __utils__['mac_utils.execute_return_result']( 'systemsetup -getcomputername') return __utils__['mac_utils.parse_return'](ret) def set_computer_name(name): ''' Set the computer name :param str name: The new computer name :return: True if successful, False if not :rtype: bool CLI Example: .. code-block:: bash salt '*' system.set_computer_name "Mike's Mac" ''' cmd = 'systemsetup -setcomputername "{0}"'.format(name) __utils__['mac_utils.execute_return_success'](cmd) return __utils__['mac_utils.confirm_updated']( name, get_computer_name, ) def get_subnet_name(): ''' Gets the local subnet name :return: The local subnet name :rtype: str CLI Example: .. code-block:: bash salt '*' system.get_subnet_name ''' ret = __utils__['mac_utils.execute_return_result']( 'systemsetup -getlocalsubnetname') return __utils__['mac_utils.parse_return'](ret) def set_subnet_name(name): ''' Set the local subnet name :param str name: The new local subnet name .. note:: Spaces are changed to dashes. Other special characters are removed. :return: True if successful, False if not :rtype: bool CLI Example: .. code-block:: bash The following will be set as 'Mikes-Mac' salt '*' system.set_subnet_name "Mike's Mac" ''' cmd = 'systemsetup -setlocalsubnetname "{0}"'.format(name) __utils__['mac_utils.execute_return_success'](cmd) return __utils__['mac_utils.confirm_updated']( name, get_subnet_name, ) def get_startup_disk(): ''' Displays the current startup disk :return: The current startup disk :rtype: str CLI Example: .. code-block:: bash salt '*' system.get_startup_disk ''' ret = __utils__['mac_utils.execute_return_result']( 'systemsetup -getstartupdisk') return __utils__['mac_utils.parse_return'](ret) def list_startup_disks(): ''' List all valid startup disks on the system. :return: A list of valid startup disks :rtype: list CLI Example: .. code-block:: bash salt '*' system.list_startup_disks ''' ret = __utils__['mac_utils.execute_return_result']( 'systemsetup -liststartupdisks') return ret.splitlines() def set_startup_disk(path): ''' Set the current startup disk to the indicated path. Use ``system.list_startup_disks`` to find valid startup disks on the system. :param str path: The valid startup disk path :return: True if successful, False if not :rtype: bool CLI Example: .. code-block:: bash salt '*' system.set_startup_disk /System/Library/CoreServices ''' if path not in list_startup_disks(): msg = 'Invalid value passed for path.\n' \ 'Must be a valid startup disk as found in ' \ 'system.list_startup_disks.\n' \ 'Passed: {0}'.format(path) raise SaltInvocationError(msg) cmd = 'systemsetup -setstartupdisk {0}'.format(path) __utils__['mac_utils.execute_return_result'](cmd) return __utils__['mac_utils.confirm_updated']( path, get_startup_disk, ) def get_restart_delay(): ''' Get the number of seconds after which the computer will start up after a power failure. :return: A string value representing the number of seconds the system will delay restart after power loss :rtype: str CLI Example: .. code-block:: bash salt '*' system.get_restart_delay ''' ret = __utils__['mac_utils.execute_return_result']( 'systemsetup -getwaitforstartupafterpowerfailure') return __utils__['mac_utils.parse_return'](ret) def set_restart_delay(seconds): ''' Set the number of seconds after which the computer will start up after a power failure. .. warning:: This command fails with the following error: ``Error, IOServiceOpen returned 0x10000003`` The setting is not updated. This is an apple bug. It seems like it may only work on certain versions of Mac Server X. This article explains the issue in more detail, though it is quite old. http://lists.apple.com/archives/macos-x-server/2006/Jul/msg00967.html :param int seconds: The number of seconds. Must be a multiple of 30 :return: True if successful, False if not :rtype: bool CLI Example: .. code-block:: bash salt '*' system.set_restart_delay 180 ''' if seconds % 30 != 0: msg = 'Invalid value passed for seconds.\n' \ 'Must be a multiple of 30.\n' \ 'Passed: {0}'.format(seconds) raise SaltInvocationError(msg) cmd = 'systemsetup -setwaitforstartupafterpowerfailure {0}'.format(seconds) __utils__['mac_utils.execute_return_success'](cmd) return __utils__['mac_utils.confirm_updated']( seconds, get_restart_delay, ) def get_disable_keyboard_on_lock(): ''' Get whether or not the keyboard should be disabled when the X Serve enclosure lock is engaged. :return: True if disable keyboard on lock is on, False if off :rtype: bool CLI Example: ..code-block:: bash salt '*' system.get_disable_keyboard_on_lock ''' ret = __utils__['mac_utils.execute_return_result']( 'systemsetup -getdisablekeyboardwhenenclosurelockisengaged') enabled = __utils__['mac_utils.validate_enabled']( __utils__['mac_utils.parse_return'](ret)) return enabled == 'on' def set_disable_keyboard_on_lock(enable): ''' Get whether or not the keyboard should be disabled when the X Serve enclosure lock is engaged. :param bool enable: True to enable, False to disable. "On" and "Off" are also acceptable values. Additionally you can pass 1 and 0 to represent True and False respectively :return: True if successful, False if not :rtype: bool CLI Example: .. code-block:: bash salt '*' system.set_disable_keyboard_on_lock False ''' state = __utils__['mac_utils.validate_enabled'](enable) cmd = 'systemsetup -setdisablekeyboardwhenenclosurelockisengaged ' \ '{0}'.format(state) __utils__['mac_utils.execute_return_success'](cmd) return __utils__['mac_utils.confirm_updated']( state, get_disable_keyboard_on_lock, normalize_ret=True, ) def get_boot_arch(): ''' Get the kernel architecture setting from ``com.apple.Boot.plist`` :return: A string value representing the boot architecture setting :rtype: str CLI Example: .. code-block:: bash salt '*' system.get_boot_arch ''' ret = __utils__['mac_utils.execute_return_result']( 'systemsetup -getkernelbootarchitecturesetting') arch = __utils__['mac_utils.parse_return'](ret) if 'default' in arch: return 'default' elif 'i386' in arch: return 'i386' elif 'x86_64' in arch: return 'x86_64' return 'unknown' def set_boot_arch(arch='default'): ''' Set the kernel to boot in 32 or 64 bit mode on next boot. .. note:: When this function fails with the error ``changes to kernel architecture failed to save!``, then the boot arch is not updated. This is either an Apple bug, not available on the test system, or a result of system files being locked down in macOS (SIP Protection). :param str arch: A string representing the desired architecture. If no value is passed, default is assumed. Valid values include: - i386 - x86_64 - default :return: True if successful, False if not :rtype: bool CLI Example: .. code-block:: bash salt '*' system.set_boot_arch i386 ''' if arch not in ['i386', 'x86_64', 'default']: msg = 'Invalid value passed for arch.\n' \ 'Must be i386, x86_64, or default.\n' \ 'Passed: {0}'.format(arch) raise SaltInvocationError(msg) cmd = 'systemsetup -setkernelbootarchitecture {0}'.format(arch) __utils__['mac_utils.execute_return_success'](cmd) return __utils__['mac_utils.confirm_updated']( arch, get_boot_arch, )
saltstack/salt
salt/modules/mac_system.py
set_remote_events
python
def set_remote_events(enable): ''' Set whether the server responds to events sent by other computers (such as AppleScripts) :param bool enable: True to enable, False to disable. "On" and "Off" are also acceptable values. Additionally you can pass 1 and 0 to represent True and False respectively :return: True if successful, False if not :rtype: bool CLI Example: .. code-block:: bash salt '*' system.set_remote_events On ''' state = __utils__['mac_utils.validate_enabled'](enable) cmd = 'systemsetup -setremoteappleevents {0}'.format(state) __utils__['mac_utils.execute_return_success'](cmd) return __utils__['mac_utils.confirm_updated']( state, get_remote_events, normalize_ret=True, )
Set whether the server responds to events sent by other computers (such as AppleScripts) :param bool enable: True to enable, False to disable. "On" and "Off" are also acceptable values. Additionally you can pass 1 and 0 to represent True and False respectively :return: True if successful, False if not :rtype: bool CLI Example: .. code-block:: bash salt '*' system.set_remote_events On
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/mac_system.py#L270-L297
null
# -*- coding: utf-8 -*- ''' System module for sleeping, restarting, and shutting down the system on Mac OS X .. versionadded:: 2016.3.0 .. warning:: Using this module will enable ``atrun`` on the system if it is disabled. ''' from __future__ import absolute_import, unicode_literals, print_function # Import python libs try: # python 3 from shlex import quote as _cmd_quote # pylint: disable=E0611 except ImportError: # python 2 from pipes import quote as _cmd_quote import getpass # Import salt libs import salt.utils.platform from salt.exceptions import SaltInvocationError, CommandExecutionError __virtualname__ = 'system' def __virtual__(): ''' Only for MacOS with atrun enabled ''' if not salt.utils.platform.is_darwin(): return (False, 'The mac_system module could not be loaded: ' 'module only works on MacOS systems.') if getpass.getuser() != 'root': return False, 'The mac_system module is not useful for non-root users.' if not _atrun_enabled(): if not _enable_atrun(): return False, 'atrun could not be enabled on this system' return __virtualname__ def _atrun_enabled(): ''' Check to see if atrun is running and enabled on the system ''' try: return __salt__['service.list']('com.apple.atrun') except CommandExecutionError: return False def _enable_atrun(): ''' Enable and start the atrun daemon ''' name = 'com.apple.atrun' try: __salt__['service.enable'](name) __salt__['service.start'](name) except CommandExecutionError: return False return _atrun_enabled() def _execute_command(cmd, at_time=None): ''' Helper function to execute the command :param str cmd: the command to run :param str at_time: If passed, the cmd will be scheduled. Returns: bool ''' if at_time: cmd = 'echo \'{0}\' | at {1}'.format(cmd, _cmd_quote(at_time)) return not bool(__salt__['cmd.retcode'](cmd, python_shell=True)) def halt(at_time=None): ''' Halt a running system :param str at_time: Any valid `at` expression. For example, some valid at expressions could be: - noon - midnight - fri - 9:00 AM - 2:30 PM tomorrow - now + 10 minutes .. note:: If you pass a time only, with no 'AM/PM' designation, you have to double quote the parameter on the command line. For example: '"14:00"' CLI Example: .. code-block:: bash salt '*' system.halt salt '*' system.halt 'now + 10 minutes' ''' cmd = 'shutdown -h now' return _execute_command(cmd, at_time) def sleep(at_time=None): ''' Sleep the system. If a user is active on the system it will likely fail to sleep. :param str at_time: Any valid `at` expression. For example, some valid at expressions could be: - noon - midnight - fri - 9:00 AM - 2:30 PM tomorrow - now + 10 minutes .. note:: If you pass a time only, with no 'AM/PM' designation, you have to double quote the parameter on the command line. For example: '"14:00"' CLI Example: .. code-block:: bash salt '*' system.sleep salt '*' system.sleep '10:00 PM' ''' cmd = 'shutdown -s now' return _execute_command(cmd, at_time) def restart(at_time=None): ''' Restart the system :param str at_time: Any valid `at` expression. For example, some valid at expressions could be: - noon - midnight - fri - 9:00 AM - 2:30 PM tomorrow - now + 10 minutes .. note:: If you pass a time only, with no 'AM/PM' designation, you have to double quote the parameter on the command line. For example: '"14:00"' CLI Example: .. code-block:: bash salt '*' system.restart salt '*' system.restart '12:00 PM fri' ''' cmd = 'shutdown -r now' return _execute_command(cmd, at_time) def shutdown(at_time=None): ''' Shutdown the system :param str at_time: Any valid `at` expression. For example, some valid at expressions could be: - noon - midnight - fri - 9:00 AM - 2:30 PM tomorrow - now + 10 minutes .. note:: If you pass a time only, with no 'AM/PM' designation, you have to double quote the parameter on the command line. For example: '"14:00"' CLI Example: .. code-block:: bash salt '*' system.shutdown salt '*' system.shutdown 'now + 1 hour' ''' return halt(at_time) def get_remote_login(): ''' Displays whether remote login (SSH) is on or off. :return: True if remote login is on, False if off :rtype: bool CLI Example: .. code-block:: bash salt '*' system.get_remote_login ''' ret = __utils__['mac_utils.execute_return_result']( 'systemsetup -getremotelogin') enabled = __utils__['mac_utils.validate_enabled']( __utils__['mac_utils.parse_return'](ret)) return enabled == 'on' def set_remote_login(enable): ''' Set the remote login (SSH) to either on or off. :param bool enable: True to enable, False to disable. "On" and "Off" are also acceptable values. Additionally you can pass 1 and 0 to represent True and False respectively :return: True if successful, False if not :rtype: bool CLI Example: .. code-block:: bash salt '*' system.set_remote_login True ''' state = __utils__['mac_utils.validate_enabled'](enable) cmd = 'systemsetup -f -setremotelogin {0}'.format(state) __utils__['mac_utils.execute_return_success'](cmd) return __utils__['mac_utils.confirm_updated'](state, get_remote_login, normalize_ret=True) def get_remote_events(): ''' Displays whether remote apple events are on or off. :return: True if remote apple events are on, False if off :rtype: bool CLI Example: .. code-block:: bash salt '*' system.get_remote_events ''' ret = __utils__['mac_utils.execute_return_result']( 'systemsetup -getremoteappleevents') enabled = __utils__['mac_utils.validate_enabled']( __utils__['mac_utils.parse_return'](ret)) return enabled == 'on' def get_computer_name(): ''' Gets the computer name :return: The computer name :rtype: str CLI Example: .. code-block:: bash salt '*' system.get_computer_name ''' ret = __utils__['mac_utils.execute_return_result']( 'systemsetup -getcomputername') return __utils__['mac_utils.parse_return'](ret) def set_computer_name(name): ''' Set the computer name :param str name: The new computer name :return: True if successful, False if not :rtype: bool CLI Example: .. code-block:: bash salt '*' system.set_computer_name "Mike's Mac" ''' cmd = 'systemsetup -setcomputername "{0}"'.format(name) __utils__['mac_utils.execute_return_success'](cmd) return __utils__['mac_utils.confirm_updated']( name, get_computer_name, ) def get_subnet_name(): ''' Gets the local subnet name :return: The local subnet name :rtype: str CLI Example: .. code-block:: bash salt '*' system.get_subnet_name ''' ret = __utils__['mac_utils.execute_return_result']( 'systemsetup -getlocalsubnetname') return __utils__['mac_utils.parse_return'](ret) def set_subnet_name(name): ''' Set the local subnet name :param str name: The new local subnet name .. note:: Spaces are changed to dashes. Other special characters are removed. :return: True if successful, False if not :rtype: bool CLI Example: .. code-block:: bash The following will be set as 'Mikes-Mac' salt '*' system.set_subnet_name "Mike's Mac" ''' cmd = 'systemsetup -setlocalsubnetname "{0}"'.format(name) __utils__['mac_utils.execute_return_success'](cmd) return __utils__['mac_utils.confirm_updated']( name, get_subnet_name, ) def get_startup_disk(): ''' Displays the current startup disk :return: The current startup disk :rtype: str CLI Example: .. code-block:: bash salt '*' system.get_startup_disk ''' ret = __utils__['mac_utils.execute_return_result']( 'systemsetup -getstartupdisk') return __utils__['mac_utils.parse_return'](ret) def list_startup_disks(): ''' List all valid startup disks on the system. :return: A list of valid startup disks :rtype: list CLI Example: .. code-block:: bash salt '*' system.list_startup_disks ''' ret = __utils__['mac_utils.execute_return_result']( 'systemsetup -liststartupdisks') return ret.splitlines() def set_startup_disk(path): ''' Set the current startup disk to the indicated path. Use ``system.list_startup_disks`` to find valid startup disks on the system. :param str path: The valid startup disk path :return: True if successful, False if not :rtype: bool CLI Example: .. code-block:: bash salt '*' system.set_startup_disk /System/Library/CoreServices ''' if path not in list_startup_disks(): msg = 'Invalid value passed for path.\n' \ 'Must be a valid startup disk as found in ' \ 'system.list_startup_disks.\n' \ 'Passed: {0}'.format(path) raise SaltInvocationError(msg) cmd = 'systemsetup -setstartupdisk {0}'.format(path) __utils__['mac_utils.execute_return_result'](cmd) return __utils__['mac_utils.confirm_updated']( path, get_startup_disk, ) def get_restart_delay(): ''' Get the number of seconds after which the computer will start up after a power failure. :return: A string value representing the number of seconds the system will delay restart after power loss :rtype: str CLI Example: .. code-block:: bash salt '*' system.get_restart_delay ''' ret = __utils__['mac_utils.execute_return_result']( 'systemsetup -getwaitforstartupafterpowerfailure') return __utils__['mac_utils.parse_return'](ret) def set_restart_delay(seconds): ''' Set the number of seconds after which the computer will start up after a power failure. .. warning:: This command fails with the following error: ``Error, IOServiceOpen returned 0x10000003`` The setting is not updated. This is an apple bug. It seems like it may only work on certain versions of Mac Server X. This article explains the issue in more detail, though it is quite old. http://lists.apple.com/archives/macos-x-server/2006/Jul/msg00967.html :param int seconds: The number of seconds. Must be a multiple of 30 :return: True if successful, False if not :rtype: bool CLI Example: .. code-block:: bash salt '*' system.set_restart_delay 180 ''' if seconds % 30 != 0: msg = 'Invalid value passed for seconds.\n' \ 'Must be a multiple of 30.\n' \ 'Passed: {0}'.format(seconds) raise SaltInvocationError(msg) cmd = 'systemsetup -setwaitforstartupafterpowerfailure {0}'.format(seconds) __utils__['mac_utils.execute_return_success'](cmd) return __utils__['mac_utils.confirm_updated']( seconds, get_restart_delay, ) def get_disable_keyboard_on_lock(): ''' Get whether or not the keyboard should be disabled when the X Serve enclosure lock is engaged. :return: True if disable keyboard on lock is on, False if off :rtype: bool CLI Example: ..code-block:: bash salt '*' system.get_disable_keyboard_on_lock ''' ret = __utils__['mac_utils.execute_return_result']( 'systemsetup -getdisablekeyboardwhenenclosurelockisengaged') enabled = __utils__['mac_utils.validate_enabled']( __utils__['mac_utils.parse_return'](ret)) return enabled == 'on' def set_disable_keyboard_on_lock(enable): ''' Get whether or not the keyboard should be disabled when the X Serve enclosure lock is engaged. :param bool enable: True to enable, False to disable. "On" and "Off" are also acceptable values. Additionally you can pass 1 and 0 to represent True and False respectively :return: True if successful, False if not :rtype: bool CLI Example: .. code-block:: bash salt '*' system.set_disable_keyboard_on_lock False ''' state = __utils__['mac_utils.validate_enabled'](enable) cmd = 'systemsetup -setdisablekeyboardwhenenclosurelockisengaged ' \ '{0}'.format(state) __utils__['mac_utils.execute_return_success'](cmd) return __utils__['mac_utils.confirm_updated']( state, get_disable_keyboard_on_lock, normalize_ret=True, ) def get_boot_arch(): ''' Get the kernel architecture setting from ``com.apple.Boot.plist`` :return: A string value representing the boot architecture setting :rtype: str CLI Example: .. code-block:: bash salt '*' system.get_boot_arch ''' ret = __utils__['mac_utils.execute_return_result']( 'systemsetup -getkernelbootarchitecturesetting') arch = __utils__['mac_utils.parse_return'](ret) if 'default' in arch: return 'default' elif 'i386' in arch: return 'i386' elif 'x86_64' in arch: return 'x86_64' return 'unknown' def set_boot_arch(arch='default'): ''' Set the kernel to boot in 32 or 64 bit mode on next boot. .. note:: When this function fails with the error ``changes to kernel architecture failed to save!``, then the boot arch is not updated. This is either an Apple bug, not available on the test system, or a result of system files being locked down in macOS (SIP Protection). :param str arch: A string representing the desired architecture. If no value is passed, default is assumed. Valid values include: - i386 - x86_64 - default :return: True if successful, False if not :rtype: bool CLI Example: .. code-block:: bash salt '*' system.set_boot_arch i386 ''' if arch not in ['i386', 'x86_64', 'default']: msg = 'Invalid value passed for arch.\n' \ 'Must be i386, x86_64, or default.\n' \ 'Passed: {0}'.format(arch) raise SaltInvocationError(msg) cmd = 'systemsetup -setkernelbootarchitecture {0}'.format(arch) __utils__['mac_utils.execute_return_success'](cmd) return __utils__['mac_utils.confirm_updated']( arch, get_boot_arch, )
saltstack/salt
salt/modules/mac_system.py
set_computer_name
python
def set_computer_name(name): ''' Set the computer name :param str name: The new computer name :return: True if successful, False if not :rtype: bool CLI Example: .. code-block:: bash salt '*' system.set_computer_name "Mike's Mac" ''' cmd = 'systemsetup -setcomputername "{0}"'.format(name) __utils__['mac_utils.execute_return_success'](cmd) return __utils__['mac_utils.confirm_updated']( name, get_computer_name, )
Set the computer name :param str name: The new computer name :return: True if successful, False if not :rtype: bool CLI Example: .. code-block:: bash salt '*' system.set_computer_name "Mike's Mac"
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/mac_system.py#L319-L340
null
# -*- coding: utf-8 -*- ''' System module for sleeping, restarting, and shutting down the system on Mac OS X .. versionadded:: 2016.3.0 .. warning:: Using this module will enable ``atrun`` on the system if it is disabled. ''' from __future__ import absolute_import, unicode_literals, print_function # Import python libs try: # python 3 from shlex import quote as _cmd_quote # pylint: disable=E0611 except ImportError: # python 2 from pipes import quote as _cmd_quote import getpass # Import salt libs import salt.utils.platform from salt.exceptions import SaltInvocationError, CommandExecutionError __virtualname__ = 'system' def __virtual__(): ''' Only for MacOS with atrun enabled ''' if not salt.utils.platform.is_darwin(): return (False, 'The mac_system module could not be loaded: ' 'module only works on MacOS systems.') if getpass.getuser() != 'root': return False, 'The mac_system module is not useful for non-root users.' if not _atrun_enabled(): if not _enable_atrun(): return False, 'atrun could not be enabled on this system' return __virtualname__ def _atrun_enabled(): ''' Check to see if atrun is running and enabled on the system ''' try: return __salt__['service.list']('com.apple.atrun') except CommandExecutionError: return False def _enable_atrun(): ''' Enable and start the atrun daemon ''' name = 'com.apple.atrun' try: __salt__['service.enable'](name) __salt__['service.start'](name) except CommandExecutionError: return False return _atrun_enabled() def _execute_command(cmd, at_time=None): ''' Helper function to execute the command :param str cmd: the command to run :param str at_time: If passed, the cmd will be scheduled. Returns: bool ''' if at_time: cmd = 'echo \'{0}\' | at {1}'.format(cmd, _cmd_quote(at_time)) return not bool(__salt__['cmd.retcode'](cmd, python_shell=True)) def halt(at_time=None): ''' Halt a running system :param str at_time: Any valid `at` expression. For example, some valid at expressions could be: - noon - midnight - fri - 9:00 AM - 2:30 PM tomorrow - now + 10 minutes .. note:: If you pass a time only, with no 'AM/PM' designation, you have to double quote the parameter on the command line. For example: '"14:00"' CLI Example: .. code-block:: bash salt '*' system.halt salt '*' system.halt 'now + 10 minutes' ''' cmd = 'shutdown -h now' return _execute_command(cmd, at_time) def sleep(at_time=None): ''' Sleep the system. If a user is active on the system it will likely fail to sleep. :param str at_time: Any valid `at` expression. For example, some valid at expressions could be: - noon - midnight - fri - 9:00 AM - 2:30 PM tomorrow - now + 10 minutes .. note:: If you pass a time only, with no 'AM/PM' designation, you have to double quote the parameter on the command line. For example: '"14:00"' CLI Example: .. code-block:: bash salt '*' system.sleep salt '*' system.sleep '10:00 PM' ''' cmd = 'shutdown -s now' return _execute_command(cmd, at_time) def restart(at_time=None): ''' Restart the system :param str at_time: Any valid `at` expression. For example, some valid at expressions could be: - noon - midnight - fri - 9:00 AM - 2:30 PM tomorrow - now + 10 minutes .. note:: If you pass a time only, with no 'AM/PM' designation, you have to double quote the parameter on the command line. For example: '"14:00"' CLI Example: .. code-block:: bash salt '*' system.restart salt '*' system.restart '12:00 PM fri' ''' cmd = 'shutdown -r now' return _execute_command(cmd, at_time) def shutdown(at_time=None): ''' Shutdown the system :param str at_time: Any valid `at` expression. For example, some valid at expressions could be: - noon - midnight - fri - 9:00 AM - 2:30 PM tomorrow - now + 10 minutes .. note:: If you pass a time only, with no 'AM/PM' designation, you have to double quote the parameter on the command line. For example: '"14:00"' CLI Example: .. code-block:: bash salt '*' system.shutdown salt '*' system.shutdown 'now + 1 hour' ''' return halt(at_time) def get_remote_login(): ''' Displays whether remote login (SSH) is on or off. :return: True if remote login is on, False if off :rtype: bool CLI Example: .. code-block:: bash salt '*' system.get_remote_login ''' ret = __utils__['mac_utils.execute_return_result']( 'systemsetup -getremotelogin') enabled = __utils__['mac_utils.validate_enabled']( __utils__['mac_utils.parse_return'](ret)) return enabled == 'on' def set_remote_login(enable): ''' Set the remote login (SSH) to either on or off. :param bool enable: True to enable, False to disable. "On" and "Off" are also acceptable values. Additionally you can pass 1 and 0 to represent True and False respectively :return: True if successful, False if not :rtype: bool CLI Example: .. code-block:: bash salt '*' system.set_remote_login True ''' state = __utils__['mac_utils.validate_enabled'](enable) cmd = 'systemsetup -f -setremotelogin {0}'.format(state) __utils__['mac_utils.execute_return_success'](cmd) return __utils__['mac_utils.confirm_updated'](state, get_remote_login, normalize_ret=True) def get_remote_events(): ''' Displays whether remote apple events are on or off. :return: True if remote apple events are on, False if off :rtype: bool CLI Example: .. code-block:: bash salt '*' system.get_remote_events ''' ret = __utils__['mac_utils.execute_return_result']( 'systemsetup -getremoteappleevents') enabled = __utils__['mac_utils.validate_enabled']( __utils__['mac_utils.parse_return'](ret)) return enabled == 'on' def set_remote_events(enable): ''' Set whether the server responds to events sent by other computers (such as AppleScripts) :param bool enable: True to enable, False to disable. "On" and "Off" are also acceptable values. Additionally you can pass 1 and 0 to represent True and False respectively :return: True if successful, False if not :rtype: bool CLI Example: .. code-block:: bash salt '*' system.set_remote_events On ''' state = __utils__['mac_utils.validate_enabled'](enable) cmd = 'systemsetup -setremoteappleevents {0}'.format(state) __utils__['mac_utils.execute_return_success'](cmd) return __utils__['mac_utils.confirm_updated']( state, get_remote_events, normalize_ret=True, ) def get_computer_name(): ''' Gets the computer name :return: The computer name :rtype: str CLI Example: .. code-block:: bash salt '*' system.get_computer_name ''' ret = __utils__['mac_utils.execute_return_result']( 'systemsetup -getcomputername') return __utils__['mac_utils.parse_return'](ret) def get_subnet_name(): ''' Gets the local subnet name :return: The local subnet name :rtype: str CLI Example: .. code-block:: bash salt '*' system.get_subnet_name ''' ret = __utils__['mac_utils.execute_return_result']( 'systemsetup -getlocalsubnetname') return __utils__['mac_utils.parse_return'](ret) def set_subnet_name(name): ''' Set the local subnet name :param str name: The new local subnet name .. note:: Spaces are changed to dashes. Other special characters are removed. :return: True if successful, False if not :rtype: bool CLI Example: .. code-block:: bash The following will be set as 'Mikes-Mac' salt '*' system.set_subnet_name "Mike's Mac" ''' cmd = 'systemsetup -setlocalsubnetname "{0}"'.format(name) __utils__['mac_utils.execute_return_success'](cmd) return __utils__['mac_utils.confirm_updated']( name, get_subnet_name, ) def get_startup_disk(): ''' Displays the current startup disk :return: The current startup disk :rtype: str CLI Example: .. code-block:: bash salt '*' system.get_startup_disk ''' ret = __utils__['mac_utils.execute_return_result']( 'systemsetup -getstartupdisk') return __utils__['mac_utils.parse_return'](ret) def list_startup_disks(): ''' List all valid startup disks on the system. :return: A list of valid startup disks :rtype: list CLI Example: .. code-block:: bash salt '*' system.list_startup_disks ''' ret = __utils__['mac_utils.execute_return_result']( 'systemsetup -liststartupdisks') return ret.splitlines() def set_startup_disk(path): ''' Set the current startup disk to the indicated path. Use ``system.list_startup_disks`` to find valid startup disks on the system. :param str path: The valid startup disk path :return: True if successful, False if not :rtype: bool CLI Example: .. code-block:: bash salt '*' system.set_startup_disk /System/Library/CoreServices ''' if path not in list_startup_disks(): msg = 'Invalid value passed for path.\n' \ 'Must be a valid startup disk as found in ' \ 'system.list_startup_disks.\n' \ 'Passed: {0}'.format(path) raise SaltInvocationError(msg) cmd = 'systemsetup -setstartupdisk {0}'.format(path) __utils__['mac_utils.execute_return_result'](cmd) return __utils__['mac_utils.confirm_updated']( path, get_startup_disk, ) def get_restart_delay(): ''' Get the number of seconds after which the computer will start up after a power failure. :return: A string value representing the number of seconds the system will delay restart after power loss :rtype: str CLI Example: .. code-block:: bash salt '*' system.get_restart_delay ''' ret = __utils__['mac_utils.execute_return_result']( 'systemsetup -getwaitforstartupafterpowerfailure') return __utils__['mac_utils.parse_return'](ret) def set_restart_delay(seconds): ''' Set the number of seconds after which the computer will start up after a power failure. .. warning:: This command fails with the following error: ``Error, IOServiceOpen returned 0x10000003`` The setting is not updated. This is an apple bug. It seems like it may only work on certain versions of Mac Server X. This article explains the issue in more detail, though it is quite old. http://lists.apple.com/archives/macos-x-server/2006/Jul/msg00967.html :param int seconds: The number of seconds. Must be a multiple of 30 :return: True if successful, False if not :rtype: bool CLI Example: .. code-block:: bash salt '*' system.set_restart_delay 180 ''' if seconds % 30 != 0: msg = 'Invalid value passed for seconds.\n' \ 'Must be a multiple of 30.\n' \ 'Passed: {0}'.format(seconds) raise SaltInvocationError(msg) cmd = 'systemsetup -setwaitforstartupafterpowerfailure {0}'.format(seconds) __utils__['mac_utils.execute_return_success'](cmd) return __utils__['mac_utils.confirm_updated']( seconds, get_restart_delay, ) def get_disable_keyboard_on_lock(): ''' Get whether or not the keyboard should be disabled when the X Serve enclosure lock is engaged. :return: True if disable keyboard on lock is on, False if off :rtype: bool CLI Example: ..code-block:: bash salt '*' system.get_disable_keyboard_on_lock ''' ret = __utils__['mac_utils.execute_return_result']( 'systemsetup -getdisablekeyboardwhenenclosurelockisengaged') enabled = __utils__['mac_utils.validate_enabled']( __utils__['mac_utils.parse_return'](ret)) return enabled == 'on' def set_disable_keyboard_on_lock(enable): ''' Get whether or not the keyboard should be disabled when the X Serve enclosure lock is engaged. :param bool enable: True to enable, False to disable. "On" and "Off" are also acceptable values. Additionally you can pass 1 and 0 to represent True and False respectively :return: True if successful, False if not :rtype: bool CLI Example: .. code-block:: bash salt '*' system.set_disable_keyboard_on_lock False ''' state = __utils__['mac_utils.validate_enabled'](enable) cmd = 'systemsetup -setdisablekeyboardwhenenclosurelockisengaged ' \ '{0}'.format(state) __utils__['mac_utils.execute_return_success'](cmd) return __utils__['mac_utils.confirm_updated']( state, get_disable_keyboard_on_lock, normalize_ret=True, ) def get_boot_arch(): ''' Get the kernel architecture setting from ``com.apple.Boot.plist`` :return: A string value representing the boot architecture setting :rtype: str CLI Example: .. code-block:: bash salt '*' system.get_boot_arch ''' ret = __utils__['mac_utils.execute_return_result']( 'systemsetup -getkernelbootarchitecturesetting') arch = __utils__['mac_utils.parse_return'](ret) if 'default' in arch: return 'default' elif 'i386' in arch: return 'i386' elif 'x86_64' in arch: return 'x86_64' return 'unknown' def set_boot_arch(arch='default'): ''' Set the kernel to boot in 32 or 64 bit mode on next boot. .. note:: When this function fails with the error ``changes to kernel architecture failed to save!``, then the boot arch is not updated. This is either an Apple bug, not available on the test system, or a result of system files being locked down in macOS (SIP Protection). :param str arch: A string representing the desired architecture. If no value is passed, default is assumed. Valid values include: - i386 - x86_64 - default :return: True if successful, False if not :rtype: bool CLI Example: .. code-block:: bash salt '*' system.set_boot_arch i386 ''' if arch not in ['i386', 'x86_64', 'default']: msg = 'Invalid value passed for arch.\n' \ 'Must be i386, x86_64, or default.\n' \ 'Passed: {0}'.format(arch) raise SaltInvocationError(msg) cmd = 'systemsetup -setkernelbootarchitecture {0}'.format(arch) __utils__['mac_utils.execute_return_success'](cmd) return __utils__['mac_utils.confirm_updated']( arch, get_boot_arch, )
saltstack/salt
salt/modules/mac_system.py
set_subnet_name
python
def set_subnet_name(name): ''' Set the local subnet name :param str name: The new local subnet name .. note:: Spaces are changed to dashes. Other special characters are removed. :return: True if successful, False if not :rtype: bool CLI Example: .. code-block:: bash The following will be set as 'Mikes-Mac' salt '*' system.set_subnet_name "Mike's Mac" ''' cmd = 'systemsetup -setlocalsubnetname "{0}"'.format(name) __utils__['mac_utils.execute_return_success'](cmd) return __utils__['mac_utils.confirm_updated']( name, get_subnet_name, )
Set the local subnet name :param str name: The new local subnet name .. note:: Spaces are changed to dashes. Other special characters are removed. :return: True if successful, False if not :rtype: bool CLI Example: .. code-block:: bash The following will be set as 'Mikes-Mac' salt '*' system.set_subnet_name "Mike's Mac"
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/mac_system.py#L362-L387
null
# -*- coding: utf-8 -*- ''' System module for sleeping, restarting, and shutting down the system on Mac OS X .. versionadded:: 2016.3.0 .. warning:: Using this module will enable ``atrun`` on the system if it is disabled. ''' from __future__ import absolute_import, unicode_literals, print_function # Import python libs try: # python 3 from shlex import quote as _cmd_quote # pylint: disable=E0611 except ImportError: # python 2 from pipes import quote as _cmd_quote import getpass # Import salt libs import salt.utils.platform from salt.exceptions import SaltInvocationError, CommandExecutionError __virtualname__ = 'system' def __virtual__(): ''' Only for MacOS with atrun enabled ''' if not salt.utils.platform.is_darwin(): return (False, 'The mac_system module could not be loaded: ' 'module only works on MacOS systems.') if getpass.getuser() != 'root': return False, 'The mac_system module is not useful for non-root users.' if not _atrun_enabled(): if not _enable_atrun(): return False, 'atrun could not be enabled on this system' return __virtualname__ def _atrun_enabled(): ''' Check to see if atrun is running and enabled on the system ''' try: return __salt__['service.list']('com.apple.atrun') except CommandExecutionError: return False def _enable_atrun(): ''' Enable and start the atrun daemon ''' name = 'com.apple.atrun' try: __salt__['service.enable'](name) __salt__['service.start'](name) except CommandExecutionError: return False return _atrun_enabled() def _execute_command(cmd, at_time=None): ''' Helper function to execute the command :param str cmd: the command to run :param str at_time: If passed, the cmd will be scheduled. Returns: bool ''' if at_time: cmd = 'echo \'{0}\' | at {1}'.format(cmd, _cmd_quote(at_time)) return not bool(__salt__['cmd.retcode'](cmd, python_shell=True)) def halt(at_time=None): ''' Halt a running system :param str at_time: Any valid `at` expression. For example, some valid at expressions could be: - noon - midnight - fri - 9:00 AM - 2:30 PM tomorrow - now + 10 minutes .. note:: If you pass a time only, with no 'AM/PM' designation, you have to double quote the parameter on the command line. For example: '"14:00"' CLI Example: .. code-block:: bash salt '*' system.halt salt '*' system.halt 'now + 10 minutes' ''' cmd = 'shutdown -h now' return _execute_command(cmd, at_time) def sleep(at_time=None): ''' Sleep the system. If a user is active on the system it will likely fail to sleep. :param str at_time: Any valid `at` expression. For example, some valid at expressions could be: - noon - midnight - fri - 9:00 AM - 2:30 PM tomorrow - now + 10 minutes .. note:: If you pass a time only, with no 'AM/PM' designation, you have to double quote the parameter on the command line. For example: '"14:00"' CLI Example: .. code-block:: bash salt '*' system.sleep salt '*' system.sleep '10:00 PM' ''' cmd = 'shutdown -s now' return _execute_command(cmd, at_time) def restart(at_time=None): ''' Restart the system :param str at_time: Any valid `at` expression. For example, some valid at expressions could be: - noon - midnight - fri - 9:00 AM - 2:30 PM tomorrow - now + 10 minutes .. note:: If you pass a time only, with no 'AM/PM' designation, you have to double quote the parameter on the command line. For example: '"14:00"' CLI Example: .. code-block:: bash salt '*' system.restart salt '*' system.restart '12:00 PM fri' ''' cmd = 'shutdown -r now' return _execute_command(cmd, at_time) def shutdown(at_time=None): ''' Shutdown the system :param str at_time: Any valid `at` expression. For example, some valid at expressions could be: - noon - midnight - fri - 9:00 AM - 2:30 PM tomorrow - now + 10 minutes .. note:: If you pass a time only, with no 'AM/PM' designation, you have to double quote the parameter on the command line. For example: '"14:00"' CLI Example: .. code-block:: bash salt '*' system.shutdown salt '*' system.shutdown 'now + 1 hour' ''' return halt(at_time) def get_remote_login(): ''' Displays whether remote login (SSH) is on or off. :return: True if remote login is on, False if off :rtype: bool CLI Example: .. code-block:: bash salt '*' system.get_remote_login ''' ret = __utils__['mac_utils.execute_return_result']( 'systemsetup -getremotelogin') enabled = __utils__['mac_utils.validate_enabled']( __utils__['mac_utils.parse_return'](ret)) return enabled == 'on' def set_remote_login(enable): ''' Set the remote login (SSH) to either on or off. :param bool enable: True to enable, False to disable. "On" and "Off" are also acceptable values. Additionally you can pass 1 and 0 to represent True and False respectively :return: True if successful, False if not :rtype: bool CLI Example: .. code-block:: bash salt '*' system.set_remote_login True ''' state = __utils__['mac_utils.validate_enabled'](enable) cmd = 'systemsetup -f -setremotelogin {0}'.format(state) __utils__['mac_utils.execute_return_success'](cmd) return __utils__['mac_utils.confirm_updated'](state, get_remote_login, normalize_ret=True) def get_remote_events(): ''' Displays whether remote apple events are on or off. :return: True if remote apple events are on, False if off :rtype: bool CLI Example: .. code-block:: bash salt '*' system.get_remote_events ''' ret = __utils__['mac_utils.execute_return_result']( 'systemsetup -getremoteappleevents') enabled = __utils__['mac_utils.validate_enabled']( __utils__['mac_utils.parse_return'](ret)) return enabled == 'on' def set_remote_events(enable): ''' Set whether the server responds to events sent by other computers (such as AppleScripts) :param bool enable: True to enable, False to disable. "On" and "Off" are also acceptable values. Additionally you can pass 1 and 0 to represent True and False respectively :return: True if successful, False if not :rtype: bool CLI Example: .. code-block:: bash salt '*' system.set_remote_events On ''' state = __utils__['mac_utils.validate_enabled'](enable) cmd = 'systemsetup -setremoteappleevents {0}'.format(state) __utils__['mac_utils.execute_return_success'](cmd) return __utils__['mac_utils.confirm_updated']( state, get_remote_events, normalize_ret=True, ) def get_computer_name(): ''' Gets the computer name :return: The computer name :rtype: str CLI Example: .. code-block:: bash salt '*' system.get_computer_name ''' ret = __utils__['mac_utils.execute_return_result']( 'systemsetup -getcomputername') return __utils__['mac_utils.parse_return'](ret) def set_computer_name(name): ''' Set the computer name :param str name: The new computer name :return: True if successful, False if not :rtype: bool CLI Example: .. code-block:: bash salt '*' system.set_computer_name "Mike's Mac" ''' cmd = 'systemsetup -setcomputername "{0}"'.format(name) __utils__['mac_utils.execute_return_success'](cmd) return __utils__['mac_utils.confirm_updated']( name, get_computer_name, ) def get_subnet_name(): ''' Gets the local subnet name :return: The local subnet name :rtype: str CLI Example: .. code-block:: bash salt '*' system.get_subnet_name ''' ret = __utils__['mac_utils.execute_return_result']( 'systemsetup -getlocalsubnetname') return __utils__['mac_utils.parse_return'](ret) def get_startup_disk(): ''' Displays the current startup disk :return: The current startup disk :rtype: str CLI Example: .. code-block:: bash salt '*' system.get_startup_disk ''' ret = __utils__['mac_utils.execute_return_result']( 'systemsetup -getstartupdisk') return __utils__['mac_utils.parse_return'](ret) def list_startup_disks(): ''' List all valid startup disks on the system. :return: A list of valid startup disks :rtype: list CLI Example: .. code-block:: bash salt '*' system.list_startup_disks ''' ret = __utils__['mac_utils.execute_return_result']( 'systemsetup -liststartupdisks') return ret.splitlines() def set_startup_disk(path): ''' Set the current startup disk to the indicated path. Use ``system.list_startup_disks`` to find valid startup disks on the system. :param str path: The valid startup disk path :return: True if successful, False if not :rtype: bool CLI Example: .. code-block:: bash salt '*' system.set_startup_disk /System/Library/CoreServices ''' if path not in list_startup_disks(): msg = 'Invalid value passed for path.\n' \ 'Must be a valid startup disk as found in ' \ 'system.list_startup_disks.\n' \ 'Passed: {0}'.format(path) raise SaltInvocationError(msg) cmd = 'systemsetup -setstartupdisk {0}'.format(path) __utils__['mac_utils.execute_return_result'](cmd) return __utils__['mac_utils.confirm_updated']( path, get_startup_disk, ) def get_restart_delay(): ''' Get the number of seconds after which the computer will start up after a power failure. :return: A string value representing the number of seconds the system will delay restart after power loss :rtype: str CLI Example: .. code-block:: bash salt '*' system.get_restart_delay ''' ret = __utils__['mac_utils.execute_return_result']( 'systemsetup -getwaitforstartupafterpowerfailure') return __utils__['mac_utils.parse_return'](ret) def set_restart_delay(seconds): ''' Set the number of seconds after which the computer will start up after a power failure. .. warning:: This command fails with the following error: ``Error, IOServiceOpen returned 0x10000003`` The setting is not updated. This is an apple bug. It seems like it may only work on certain versions of Mac Server X. This article explains the issue in more detail, though it is quite old. http://lists.apple.com/archives/macos-x-server/2006/Jul/msg00967.html :param int seconds: The number of seconds. Must be a multiple of 30 :return: True if successful, False if not :rtype: bool CLI Example: .. code-block:: bash salt '*' system.set_restart_delay 180 ''' if seconds % 30 != 0: msg = 'Invalid value passed for seconds.\n' \ 'Must be a multiple of 30.\n' \ 'Passed: {0}'.format(seconds) raise SaltInvocationError(msg) cmd = 'systemsetup -setwaitforstartupafterpowerfailure {0}'.format(seconds) __utils__['mac_utils.execute_return_success'](cmd) return __utils__['mac_utils.confirm_updated']( seconds, get_restart_delay, ) def get_disable_keyboard_on_lock(): ''' Get whether or not the keyboard should be disabled when the X Serve enclosure lock is engaged. :return: True if disable keyboard on lock is on, False if off :rtype: bool CLI Example: ..code-block:: bash salt '*' system.get_disable_keyboard_on_lock ''' ret = __utils__['mac_utils.execute_return_result']( 'systemsetup -getdisablekeyboardwhenenclosurelockisengaged') enabled = __utils__['mac_utils.validate_enabled']( __utils__['mac_utils.parse_return'](ret)) return enabled == 'on' def set_disable_keyboard_on_lock(enable): ''' Get whether or not the keyboard should be disabled when the X Serve enclosure lock is engaged. :param bool enable: True to enable, False to disable. "On" and "Off" are also acceptable values. Additionally you can pass 1 and 0 to represent True and False respectively :return: True if successful, False if not :rtype: bool CLI Example: .. code-block:: bash salt '*' system.set_disable_keyboard_on_lock False ''' state = __utils__['mac_utils.validate_enabled'](enable) cmd = 'systemsetup -setdisablekeyboardwhenenclosurelockisengaged ' \ '{0}'.format(state) __utils__['mac_utils.execute_return_success'](cmd) return __utils__['mac_utils.confirm_updated']( state, get_disable_keyboard_on_lock, normalize_ret=True, ) def get_boot_arch(): ''' Get the kernel architecture setting from ``com.apple.Boot.plist`` :return: A string value representing the boot architecture setting :rtype: str CLI Example: .. code-block:: bash salt '*' system.get_boot_arch ''' ret = __utils__['mac_utils.execute_return_result']( 'systemsetup -getkernelbootarchitecturesetting') arch = __utils__['mac_utils.parse_return'](ret) if 'default' in arch: return 'default' elif 'i386' in arch: return 'i386' elif 'x86_64' in arch: return 'x86_64' return 'unknown' def set_boot_arch(arch='default'): ''' Set the kernel to boot in 32 or 64 bit mode on next boot. .. note:: When this function fails with the error ``changes to kernel architecture failed to save!``, then the boot arch is not updated. This is either an Apple bug, not available on the test system, or a result of system files being locked down in macOS (SIP Protection). :param str arch: A string representing the desired architecture. If no value is passed, default is assumed. Valid values include: - i386 - x86_64 - default :return: True if successful, False if not :rtype: bool CLI Example: .. code-block:: bash salt '*' system.set_boot_arch i386 ''' if arch not in ['i386', 'x86_64', 'default']: msg = 'Invalid value passed for arch.\n' \ 'Must be i386, x86_64, or default.\n' \ 'Passed: {0}'.format(arch) raise SaltInvocationError(msg) cmd = 'systemsetup -setkernelbootarchitecture {0}'.format(arch) __utils__['mac_utils.execute_return_success'](cmd) return __utils__['mac_utils.confirm_updated']( arch, get_boot_arch, )
saltstack/salt
salt/modules/mac_system.py
set_startup_disk
python
def set_startup_disk(path): ''' Set the current startup disk to the indicated path. Use ``system.list_startup_disks`` to find valid startup disks on the system. :param str path: The valid startup disk path :return: True if successful, False if not :rtype: bool CLI Example: .. code-block:: bash salt '*' system.set_startup_disk /System/Library/CoreServices ''' if path not in list_startup_disks(): msg = 'Invalid value passed for path.\n' \ 'Must be a valid startup disk as found in ' \ 'system.list_startup_disks.\n' \ 'Passed: {0}'.format(path) raise SaltInvocationError(msg) cmd = 'systemsetup -setstartupdisk {0}'.format(path) __utils__['mac_utils.execute_return_result'](cmd) return __utils__['mac_utils.confirm_updated']( path, get_startup_disk, )
Set the current startup disk to the indicated path. Use ``system.list_startup_disks`` to find valid startup disks on the system. :param str path: The valid startup disk path :return: True if successful, False if not :rtype: bool CLI Example: .. code-block:: bash salt '*' system.set_startup_disk /System/Library/CoreServices
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/mac_system.py#L428-L457
[ "def list_startup_disks():\n '''\n List all valid startup disks on the system.\n\n :return: A list of valid startup disks\n :rtype: list\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' system.list_startup_disks\n '''\n ret = __utils__['mac_utils.execute_return_result'](\n 'systemsetup -liststartupdisks')\n\n return ret.splitlines()\n" ]
# -*- coding: utf-8 -*- ''' System module for sleeping, restarting, and shutting down the system on Mac OS X .. versionadded:: 2016.3.0 .. warning:: Using this module will enable ``atrun`` on the system if it is disabled. ''' from __future__ import absolute_import, unicode_literals, print_function # Import python libs try: # python 3 from shlex import quote as _cmd_quote # pylint: disable=E0611 except ImportError: # python 2 from pipes import quote as _cmd_quote import getpass # Import salt libs import salt.utils.platform from salt.exceptions import SaltInvocationError, CommandExecutionError __virtualname__ = 'system' def __virtual__(): ''' Only for MacOS with atrun enabled ''' if not salt.utils.platform.is_darwin(): return (False, 'The mac_system module could not be loaded: ' 'module only works on MacOS systems.') if getpass.getuser() != 'root': return False, 'The mac_system module is not useful for non-root users.' if not _atrun_enabled(): if not _enable_atrun(): return False, 'atrun could not be enabled on this system' return __virtualname__ def _atrun_enabled(): ''' Check to see if atrun is running and enabled on the system ''' try: return __salt__['service.list']('com.apple.atrun') except CommandExecutionError: return False def _enable_atrun(): ''' Enable and start the atrun daemon ''' name = 'com.apple.atrun' try: __salt__['service.enable'](name) __salt__['service.start'](name) except CommandExecutionError: return False return _atrun_enabled() def _execute_command(cmd, at_time=None): ''' Helper function to execute the command :param str cmd: the command to run :param str at_time: If passed, the cmd will be scheduled. Returns: bool ''' if at_time: cmd = 'echo \'{0}\' | at {1}'.format(cmd, _cmd_quote(at_time)) return not bool(__salt__['cmd.retcode'](cmd, python_shell=True)) def halt(at_time=None): ''' Halt a running system :param str at_time: Any valid `at` expression. For example, some valid at expressions could be: - noon - midnight - fri - 9:00 AM - 2:30 PM tomorrow - now + 10 minutes .. note:: If you pass a time only, with no 'AM/PM' designation, you have to double quote the parameter on the command line. For example: '"14:00"' CLI Example: .. code-block:: bash salt '*' system.halt salt '*' system.halt 'now + 10 minutes' ''' cmd = 'shutdown -h now' return _execute_command(cmd, at_time) def sleep(at_time=None): ''' Sleep the system. If a user is active on the system it will likely fail to sleep. :param str at_time: Any valid `at` expression. For example, some valid at expressions could be: - noon - midnight - fri - 9:00 AM - 2:30 PM tomorrow - now + 10 minutes .. note:: If you pass a time only, with no 'AM/PM' designation, you have to double quote the parameter on the command line. For example: '"14:00"' CLI Example: .. code-block:: bash salt '*' system.sleep salt '*' system.sleep '10:00 PM' ''' cmd = 'shutdown -s now' return _execute_command(cmd, at_time) def restart(at_time=None): ''' Restart the system :param str at_time: Any valid `at` expression. For example, some valid at expressions could be: - noon - midnight - fri - 9:00 AM - 2:30 PM tomorrow - now + 10 minutes .. note:: If you pass a time only, with no 'AM/PM' designation, you have to double quote the parameter on the command line. For example: '"14:00"' CLI Example: .. code-block:: bash salt '*' system.restart salt '*' system.restart '12:00 PM fri' ''' cmd = 'shutdown -r now' return _execute_command(cmd, at_time) def shutdown(at_time=None): ''' Shutdown the system :param str at_time: Any valid `at` expression. For example, some valid at expressions could be: - noon - midnight - fri - 9:00 AM - 2:30 PM tomorrow - now + 10 minutes .. note:: If you pass a time only, with no 'AM/PM' designation, you have to double quote the parameter on the command line. For example: '"14:00"' CLI Example: .. code-block:: bash salt '*' system.shutdown salt '*' system.shutdown 'now + 1 hour' ''' return halt(at_time) def get_remote_login(): ''' Displays whether remote login (SSH) is on or off. :return: True if remote login is on, False if off :rtype: bool CLI Example: .. code-block:: bash salt '*' system.get_remote_login ''' ret = __utils__['mac_utils.execute_return_result']( 'systemsetup -getremotelogin') enabled = __utils__['mac_utils.validate_enabled']( __utils__['mac_utils.parse_return'](ret)) return enabled == 'on' def set_remote_login(enable): ''' Set the remote login (SSH) to either on or off. :param bool enable: True to enable, False to disable. "On" and "Off" are also acceptable values. Additionally you can pass 1 and 0 to represent True and False respectively :return: True if successful, False if not :rtype: bool CLI Example: .. code-block:: bash salt '*' system.set_remote_login True ''' state = __utils__['mac_utils.validate_enabled'](enable) cmd = 'systemsetup -f -setremotelogin {0}'.format(state) __utils__['mac_utils.execute_return_success'](cmd) return __utils__['mac_utils.confirm_updated'](state, get_remote_login, normalize_ret=True) def get_remote_events(): ''' Displays whether remote apple events are on or off. :return: True if remote apple events are on, False if off :rtype: bool CLI Example: .. code-block:: bash salt '*' system.get_remote_events ''' ret = __utils__['mac_utils.execute_return_result']( 'systemsetup -getremoteappleevents') enabled = __utils__['mac_utils.validate_enabled']( __utils__['mac_utils.parse_return'](ret)) return enabled == 'on' def set_remote_events(enable): ''' Set whether the server responds to events sent by other computers (such as AppleScripts) :param bool enable: True to enable, False to disable. "On" and "Off" are also acceptable values. Additionally you can pass 1 and 0 to represent True and False respectively :return: True if successful, False if not :rtype: bool CLI Example: .. code-block:: bash salt '*' system.set_remote_events On ''' state = __utils__['mac_utils.validate_enabled'](enable) cmd = 'systemsetup -setremoteappleevents {0}'.format(state) __utils__['mac_utils.execute_return_success'](cmd) return __utils__['mac_utils.confirm_updated']( state, get_remote_events, normalize_ret=True, ) def get_computer_name(): ''' Gets the computer name :return: The computer name :rtype: str CLI Example: .. code-block:: bash salt '*' system.get_computer_name ''' ret = __utils__['mac_utils.execute_return_result']( 'systemsetup -getcomputername') return __utils__['mac_utils.parse_return'](ret) def set_computer_name(name): ''' Set the computer name :param str name: The new computer name :return: True if successful, False if not :rtype: bool CLI Example: .. code-block:: bash salt '*' system.set_computer_name "Mike's Mac" ''' cmd = 'systemsetup -setcomputername "{0}"'.format(name) __utils__['mac_utils.execute_return_success'](cmd) return __utils__['mac_utils.confirm_updated']( name, get_computer_name, ) def get_subnet_name(): ''' Gets the local subnet name :return: The local subnet name :rtype: str CLI Example: .. code-block:: bash salt '*' system.get_subnet_name ''' ret = __utils__['mac_utils.execute_return_result']( 'systemsetup -getlocalsubnetname') return __utils__['mac_utils.parse_return'](ret) def set_subnet_name(name): ''' Set the local subnet name :param str name: The new local subnet name .. note:: Spaces are changed to dashes. Other special characters are removed. :return: True if successful, False if not :rtype: bool CLI Example: .. code-block:: bash The following will be set as 'Mikes-Mac' salt '*' system.set_subnet_name "Mike's Mac" ''' cmd = 'systemsetup -setlocalsubnetname "{0}"'.format(name) __utils__['mac_utils.execute_return_success'](cmd) return __utils__['mac_utils.confirm_updated']( name, get_subnet_name, ) def get_startup_disk(): ''' Displays the current startup disk :return: The current startup disk :rtype: str CLI Example: .. code-block:: bash salt '*' system.get_startup_disk ''' ret = __utils__['mac_utils.execute_return_result']( 'systemsetup -getstartupdisk') return __utils__['mac_utils.parse_return'](ret) def list_startup_disks(): ''' List all valid startup disks on the system. :return: A list of valid startup disks :rtype: list CLI Example: .. code-block:: bash salt '*' system.list_startup_disks ''' ret = __utils__['mac_utils.execute_return_result']( 'systemsetup -liststartupdisks') return ret.splitlines() def get_restart_delay(): ''' Get the number of seconds after which the computer will start up after a power failure. :return: A string value representing the number of seconds the system will delay restart after power loss :rtype: str CLI Example: .. code-block:: bash salt '*' system.get_restart_delay ''' ret = __utils__['mac_utils.execute_return_result']( 'systemsetup -getwaitforstartupafterpowerfailure') return __utils__['mac_utils.parse_return'](ret) def set_restart_delay(seconds): ''' Set the number of seconds after which the computer will start up after a power failure. .. warning:: This command fails with the following error: ``Error, IOServiceOpen returned 0x10000003`` The setting is not updated. This is an apple bug. It seems like it may only work on certain versions of Mac Server X. This article explains the issue in more detail, though it is quite old. http://lists.apple.com/archives/macos-x-server/2006/Jul/msg00967.html :param int seconds: The number of seconds. Must be a multiple of 30 :return: True if successful, False if not :rtype: bool CLI Example: .. code-block:: bash salt '*' system.set_restart_delay 180 ''' if seconds % 30 != 0: msg = 'Invalid value passed for seconds.\n' \ 'Must be a multiple of 30.\n' \ 'Passed: {0}'.format(seconds) raise SaltInvocationError(msg) cmd = 'systemsetup -setwaitforstartupafterpowerfailure {0}'.format(seconds) __utils__['mac_utils.execute_return_success'](cmd) return __utils__['mac_utils.confirm_updated']( seconds, get_restart_delay, ) def get_disable_keyboard_on_lock(): ''' Get whether or not the keyboard should be disabled when the X Serve enclosure lock is engaged. :return: True if disable keyboard on lock is on, False if off :rtype: bool CLI Example: ..code-block:: bash salt '*' system.get_disable_keyboard_on_lock ''' ret = __utils__['mac_utils.execute_return_result']( 'systemsetup -getdisablekeyboardwhenenclosurelockisengaged') enabled = __utils__['mac_utils.validate_enabled']( __utils__['mac_utils.parse_return'](ret)) return enabled == 'on' def set_disable_keyboard_on_lock(enable): ''' Get whether or not the keyboard should be disabled when the X Serve enclosure lock is engaged. :param bool enable: True to enable, False to disable. "On" and "Off" are also acceptable values. Additionally you can pass 1 and 0 to represent True and False respectively :return: True if successful, False if not :rtype: bool CLI Example: .. code-block:: bash salt '*' system.set_disable_keyboard_on_lock False ''' state = __utils__['mac_utils.validate_enabled'](enable) cmd = 'systemsetup -setdisablekeyboardwhenenclosurelockisengaged ' \ '{0}'.format(state) __utils__['mac_utils.execute_return_success'](cmd) return __utils__['mac_utils.confirm_updated']( state, get_disable_keyboard_on_lock, normalize_ret=True, ) def get_boot_arch(): ''' Get the kernel architecture setting from ``com.apple.Boot.plist`` :return: A string value representing the boot architecture setting :rtype: str CLI Example: .. code-block:: bash salt '*' system.get_boot_arch ''' ret = __utils__['mac_utils.execute_return_result']( 'systemsetup -getkernelbootarchitecturesetting') arch = __utils__['mac_utils.parse_return'](ret) if 'default' in arch: return 'default' elif 'i386' in arch: return 'i386' elif 'x86_64' in arch: return 'x86_64' return 'unknown' def set_boot_arch(arch='default'): ''' Set the kernel to boot in 32 or 64 bit mode on next boot. .. note:: When this function fails with the error ``changes to kernel architecture failed to save!``, then the boot arch is not updated. This is either an Apple bug, not available on the test system, or a result of system files being locked down in macOS (SIP Protection). :param str arch: A string representing the desired architecture. If no value is passed, default is assumed. Valid values include: - i386 - x86_64 - default :return: True if successful, False if not :rtype: bool CLI Example: .. code-block:: bash salt '*' system.set_boot_arch i386 ''' if arch not in ['i386', 'x86_64', 'default']: msg = 'Invalid value passed for arch.\n' \ 'Must be i386, x86_64, or default.\n' \ 'Passed: {0}'.format(arch) raise SaltInvocationError(msg) cmd = 'systemsetup -setkernelbootarchitecture {0}'.format(arch) __utils__['mac_utils.execute_return_success'](cmd) return __utils__['mac_utils.confirm_updated']( arch, get_boot_arch, )
saltstack/salt
salt/modules/mac_system.py
set_restart_delay
python
def set_restart_delay(seconds): ''' Set the number of seconds after which the computer will start up after a power failure. .. warning:: This command fails with the following error: ``Error, IOServiceOpen returned 0x10000003`` The setting is not updated. This is an apple bug. It seems like it may only work on certain versions of Mac Server X. This article explains the issue in more detail, though it is quite old. http://lists.apple.com/archives/macos-x-server/2006/Jul/msg00967.html :param int seconds: The number of seconds. Must be a multiple of 30 :return: True if successful, False if not :rtype: bool CLI Example: .. code-block:: bash salt '*' system.set_restart_delay 180 ''' if seconds % 30 != 0: msg = 'Invalid value passed for seconds.\n' \ 'Must be a multiple of 30.\n' \ 'Passed: {0}'.format(seconds) raise SaltInvocationError(msg) cmd = 'systemsetup -setwaitforstartupafterpowerfailure {0}'.format(seconds) __utils__['mac_utils.execute_return_success'](cmd) return __utils__['mac_utils.confirm_updated']( seconds, get_restart_delay, )
Set the number of seconds after which the computer will start up after a power failure. .. warning:: This command fails with the following error: ``Error, IOServiceOpen returned 0x10000003`` The setting is not updated. This is an apple bug. It seems like it may only work on certain versions of Mac Server X. This article explains the issue in more detail, though it is quite old. http://lists.apple.com/archives/macos-x-server/2006/Jul/msg00967.html :param int seconds: The number of seconds. Must be a multiple of 30 :return: True if successful, False if not :rtype: bool CLI Example: .. code-block:: bash salt '*' system.set_restart_delay 180
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/mac_system.py#L481-L521
null
# -*- coding: utf-8 -*- ''' System module for sleeping, restarting, and shutting down the system on Mac OS X .. versionadded:: 2016.3.0 .. warning:: Using this module will enable ``atrun`` on the system if it is disabled. ''' from __future__ import absolute_import, unicode_literals, print_function # Import python libs try: # python 3 from shlex import quote as _cmd_quote # pylint: disable=E0611 except ImportError: # python 2 from pipes import quote as _cmd_quote import getpass # Import salt libs import salt.utils.platform from salt.exceptions import SaltInvocationError, CommandExecutionError __virtualname__ = 'system' def __virtual__(): ''' Only for MacOS with atrun enabled ''' if not salt.utils.platform.is_darwin(): return (False, 'The mac_system module could not be loaded: ' 'module only works on MacOS systems.') if getpass.getuser() != 'root': return False, 'The mac_system module is not useful for non-root users.' if not _atrun_enabled(): if not _enable_atrun(): return False, 'atrun could not be enabled on this system' return __virtualname__ def _atrun_enabled(): ''' Check to see if atrun is running and enabled on the system ''' try: return __salt__['service.list']('com.apple.atrun') except CommandExecutionError: return False def _enable_atrun(): ''' Enable and start the atrun daemon ''' name = 'com.apple.atrun' try: __salt__['service.enable'](name) __salt__['service.start'](name) except CommandExecutionError: return False return _atrun_enabled() def _execute_command(cmd, at_time=None): ''' Helper function to execute the command :param str cmd: the command to run :param str at_time: If passed, the cmd will be scheduled. Returns: bool ''' if at_time: cmd = 'echo \'{0}\' | at {1}'.format(cmd, _cmd_quote(at_time)) return not bool(__salt__['cmd.retcode'](cmd, python_shell=True)) def halt(at_time=None): ''' Halt a running system :param str at_time: Any valid `at` expression. For example, some valid at expressions could be: - noon - midnight - fri - 9:00 AM - 2:30 PM tomorrow - now + 10 minutes .. note:: If you pass a time only, with no 'AM/PM' designation, you have to double quote the parameter on the command line. For example: '"14:00"' CLI Example: .. code-block:: bash salt '*' system.halt salt '*' system.halt 'now + 10 minutes' ''' cmd = 'shutdown -h now' return _execute_command(cmd, at_time) def sleep(at_time=None): ''' Sleep the system. If a user is active on the system it will likely fail to sleep. :param str at_time: Any valid `at` expression. For example, some valid at expressions could be: - noon - midnight - fri - 9:00 AM - 2:30 PM tomorrow - now + 10 minutes .. note:: If you pass a time only, with no 'AM/PM' designation, you have to double quote the parameter on the command line. For example: '"14:00"' CLI Example: .. code-block:: bash salt '*' system.sleep salt '*' system.sleep '10:00 PM' ''' cmd = 'shutdown -s now' return _execute_command(cmd, at_time) def restart(at_time=None): ''' Restart the system :param str at_time: Any valid `at` expression. For example, some valid at expressions could be: - noon - midnight - fri - 9:00 AM - 2:30 PM tomorrow - now + 10 minutes .. note:: If you pass a time only, with no 'AM/PM' designation, you have to double quote the parameter on the command line. For example: '"14:00"' CLI Example: .. code-block:: bash salt '*' system.restart salt '*' system.restart '12:00 PM fri' ''' cmd = 'shutdown -r now' return _execute_command(cmd, at_time) def shutdown(at_time=None): ''' Shutdown the system :param str at_time: Any valid `at` expression. For example, some valid at expressions could be: - noon - midnight - fri - 9:00 AM - 2:30 PM tomorrow - now + 10 minutes .. note:: If you pass a time only, with no 'AM/PM' designation, you have to double quote the parameter on the command line. For example: '"14:00"' CLI Example: .. code-block:: bash salt '*' system.shutdown salt '*' system.shutdown 'now + 1 hour' ''' return halt(at_time) def get_remote_login(): ''' Displays whether remote login (SSH) is on or off. :return: True if remote login is on, False if off :rtype: bool CLI Example: .. code-block:: bash salt '*' system.get_remote_login ''' ret = __utils__['mac_utils.execute_return_result']( 'systemsetup -getremotelogin') enabled = __utils__['mac_utils.validate_enabled']( __utils__['mac_utils.parse_return'](ret)) return enabled == 'on' def set_remote_login(enable): ''' Set the remote login (SSH) to either on or off. :param bool enable: True to enable, False to disable. "On" and "Off" are also acceptable values. Additionally you can pass 1 and 0 to represent True and False respectively :return: True if successful, False if not :rtype: bool CLI Example: .. code-block:: bash salt '*' system.set_remote_login True ''' state = __utils__['mac_utils.validate_enabled'](enable) cmd = 'systemsetup -f -setremotelogin {0}'.format(state) __utils__['mac_utils.execute_return_success'](cmd) return __utils__['mac_utils.confirm_updated'](state, get_remote_login, normalize_ret=True) def get_remote_events(): ''' Displays whether remote apple events are on or off. :return: True if remote apple events are on, False if off :rtype: bool CLI Example: .. code-block:: bash salt '*' system.get_remote_events ''' ret = __utils__['mac_utils.execute_return_result']( 'systemsetup -getremoteappleevents') enabled = __utils__['mac_utils.validate_enabled']( __utils__['mac_utils.parse_return'](ret)) return enabled == 'on' def set_remote_events(enable): ''' Set whether the server responds to events sent by other computers (such as AppleScripts) :param bool enable: True to enable, False to disable. "On" and "Off" are also acceptable values. Additionally you can pass 1 and 0 to represent True and False respectively :return: True if successful, False if not :rtype: bool CLI Example: .. code-block:: bash salt '*' system.set_remote_events On ''' state = __utils__['mac_utils.validate_enabled'](enable) cmd = 'systemsetup -setremoteappleevents {0}'.format(state) __utils__['mac_utils.execute_return_success'](cmd) return __utils__['mac_utils.confirm_updated']( state, get_remote_events, normalize_ret=True, ) def get_computer_name(): ''' Gets the computer name :return: The computer name :rtype: str CLI Example: .. code-block:: bash salt '*' system.get_computer_name ''' ret = __utils__['mac_utils.execute_return_result']( 'systemsetup -getcomputername') return __utils__['mac_utils.parse_return'](ret) def set_computer_name(name): ''' Set the computer name :param str name: The new computer name :return: True if successful, False if not :rtype: bool CLI Example: .. code-block:: bash salt '*' system.set_computer_name "Mike's Mac" ''' cmd = 'systemsetup -setcomputername "{0}"'.format(name) __utils__['mac_utils.execute_return_success'](cmd) return __utils__['mac_utils.confirm_updated']( name, get_computer_name, ) def get_subnet_name(): ''' Gets the local subnet name :return: The local subnet name :rtype: str CLI Example: .. code-block:: bash salt '*' system.get_subnet_name ''' ret = __utils__['mac_utils.execute_return_result']( 'systemsetup -getlocalsubnetname') return __utils__['mac_utils.parse_return'](ret) def set_subnet_name(name): ''' Set the local subnet name :param str name: The new local subnet name .. note:: Spaces are changed to dashes. Other special characters are removed. :return: True if successful, False if not :rtype: bool CLI Example: .. code-block:: bash The following will be set as 'Mikes-Mac' salt '*' system.set_subnet_name "Mike's Mac" ''' cmd = 'systemsetup -setlocalsubnetname "{0}"'.format(name) __utils__['mac_utils.execute_return_success'](cmd) return __utils__['mac_utils.confirm_updated']( name, get_subnet_name, ) def get_startup_disk(): ''' Displays the current startup disk :return: The current startup disk :rtype: str CLI Example: .. code-block:: bash salt '*' system.get_startup_disk ''' ret = __utils__['mac_utils.execute_return_result']( 'systemsetup -getstartupdisk') return __utils__['mac_utils.parse_return'](ret) def list_startup_disks(): ''' List all valid startup disks on the system. :return: A list of valid startup disks :rtype: list CLI Example: .. code-block:: bash salt '*' system.list_startup_disks ''' ret = __utils__['mac_utils.execute_return_result']( 'systemsetup -liststartupdisks') return ret.splitlines() def set_startup_disk(path): ''' Set the current startup disk to the indicated path. Use ``system.list_startup_disks`` to find valid startup disks on the system. :param str path: The valid startup disk path :return: True if successful, False if not :rtype: bool CLI Example: .. code-block:: bash salt '*' system.set_startup_disk /System/Library/CoreServices ''' if path not in list_startup_disks(): msg = 'Invalid value passed for path.\n' \ 'Must be a valid startup disk as found in ' \ 'system.list_startup_disks.\n' \ 'Passed: {0}'.format(path) raise SaltInvocationError(msg) cmd = 'systemsetup -setstartupdisk {0}'.format(path) __utils__['mac_utils.execute_return_result'](cmd) return __utils__['mac_utils.confirm_updated']( path, get_startup_disk, ) def get_restart_delay(): ''' Get the number of seconds after which the computer will start up after a power failure. :return: A string value representing the number of seconds the system will delay restart after power loss :rtype: str CLI Example: .. code-block:: bash salt '*' system.get_restart_delay ''' ret = __utils__['mac_utils.execute_return_result']( 'systemsetup -getwaitforstartupafterpowerfailure') return __utils__['mac_utils.parse_return'](ret) def get_disable_keyboard_on_lock(): ''' Get whether or not the keyboard should be disabled when the X Serve enclosure lock is engaged. :return: True if disable keyboard on lock is on, False if off :rtype: bool CLI Example: ..code-block:: bash salt '*' system.get_disable_keyboard_on_lock ''' ret = __utils__['mac_utils.execute_return_result']( 'systemsetup -getdisablekeyboardwhenenclosurelockisengaged') enabled = __utils__['mac_utils.validate_enabled']( __utils__['mac_utils.parse_return'](ret)) return enabled == 'on' def set_disable_keyboard_on_lock(enable): ''' Get whether or not the keyboard should be disabled when the X Serve enclosure lock is engaged. :param bool enable: True to enable, False to disable. "On" and "Off" are also acceptable values. Additionally you can pass 1 and 0 to represent True and False respectively :return: True if successful, False if not :rtype: bool CLI Example: .. code-block:: bash salt '*' system.set_disable_keyboard_on_lock False ''' state = __utils__['mac_utils.validate_enabled'](enable) cmd = 'systemsetup -setdisablekeyboardwhenenclosurelockisengaged ' \ '{0}'.format(state) __utils__['mac_utils.execute_return_success'](cmd) return __utils__['mac_utils.confirm_updated']( state, get_disable_keyboard_on_lock, normalize_ret=True, ) def get_boot_arch(): ''' Get the kernel architecture setting from ``com.apple.Boot.plist`` :return: A string value representing the boot architecture setting :rtype: str CLI Example: .. code-block:: bash salt '*' system.get_boot_arch ''' ret = __utils__['mac_utils.execute_return_result']( 'systemsetup -getkernelbootarchitecturesetting') arch = __utils__['mac_utils.parse_return'](ret) if 'default' in arch: return 'default' elif 'i386' in arch: return 'i386' elif 'x86_64' in arch: return 'x86_64' return 'unknown' def set_boot_arch(arch='default'): ''' Set the kernel to boot in 32 or 64 bit mode on next boot. .. note:: When this function fails with the error ``changes to kernel architecture failed to save!``, then the boot arch is not updated. This is either an Apple bug, not available on the test system, or a result of system files being locked down in macOS (SIP Protection). :param str arch: A string representing the desired architecture. If no value is passed, default is assumed. Valid values include: - i386 - x86_64 - default :return: True if successful, False if not :rtype: bool CLI Example: .. code-block:: bash salt '*' system.set_boot_arch i386 ''' if arch not in ['i386', 'x86_64', 'default']: msg = 'Invalid value passed for arch.\n' \ 'Must be i386, x86_64, or default.\n' \ 'Passed: {0}'.format(arch) raise SaltInvocationError(msg) cmd = 'systemsetup -setkernelbootarchitecture {0}'.format(arch) __utils__['mac_utils.execute_return_success'](cmd) return __utils__['mac_utils.confirm_updated']( arch, get_boot_arch, )
saltstack/salt
salt/modules/mac_system.py
set_disable_keyboard_on_lock
python
def set_disable_keyboard_on_lock(enable): ''' Get whether or not the keyboard should be disabled when the X Serve enclosure lock is engaged. :param bool enable: True to enable, False to disable. "On" and "Off" are also acceptable values. Additionally you can pass 1 and 0 to represent True and False respectively :return: True if successful, False if not :rtype: bool CLI Example: .. code-block:: bash salt '*' system.set_disable_keyboard_on_lock False ''' state = __utils__['mac_utils.validate_enabled'](enable) cmd = 'systemsetup -setdisablekeyboardwhenenclosurelockisengaged ' \ '{0}'.format(state) __utils__['mac_utils.execute_return_success'](cmd) return __utils__['mac_utils.confirm_updated']( state, get_disable_keyboard_on_lock, normalize_ret=True, )
Get whether or not the keyboard should be disabled when the X Serve enclosure lock is engaged. :param bool enable: True to enable, False to disable. "On" and "Off" are also acceptable values. Additionally you can pass 1 and 0 to represent True and False respectively :return: True if successful, False if not :rtype: bool CLI Example: .. code-block:: bash salt '*' system.set_disable_keyboard_on_lock False
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/mac_system.py#L547-L575
null
# -*- coding: utf-8 -*- ''' System module for sleeping, restarting, and shutting down the system on Mac OS X .. versionadded:: 2016.3.0 .. warning:: Using this module will enable ``atrun`` on the system if it is disabled. ''' from __future__ import absolute_import, unicode_literals, print_function # Import python libs try: # python 3 from shlex import quote as _cmd_quote # pylint: disable=E0611 except ImportError: # python 2 from pipes import quote as _cmd_quote import getpass # Import salt libs import salt.utils.platform from salt.exceptions import SaltInvocationError, CommandExecutionError __virtualname__ = 'system' def __virtual__(): ''' Only for MacOS with atrun enabled ''' if not salt.utils.platform.is_darwin(): return (False, 'The mac_system module could not be loaded: ' 'module only works on MacOS systems.') if getpass.getuser() != 'root': return False, 'The mac_system module is not useful for non-root users.' if not _atrun_enabled(): if not _enable_atrun(): return False, 'atrun could not be enabled on this system' return __virtualname__ def _atrun_enabled(): ''' Check to see if atrun is running and enabled on the system ''' try: return __salt__['service.list']('com.apple.atrun') except CommandExecutionError: return False def _enable_atrun(): ''' Enable and start the atrun daemon ''' name = 'com.apple.atrun' try: __salt__['service.enable'](name) __salt__['service.start'](name) except CommandExecutionError: return False return _atrun_enabled() def _execute_command(cmd, at_time=None): ''' Helper function to execute the command :param str cmd: the command to run :param str at_time: If passed, the cmd will be scheduled. Returns: bool ''' if at_time: cmd = 'echo \'{0}\' | at {1}'.format(cmd, _cmd_quote(at_time)) return not bool(__salt__['cmd.retcode'](cmd, python_shell=True)) def halt(at_time=None): ''' Halt a running system :param str at_time: Any valid `at` expression. For example, some valid at expressions could be: - noon - midnight - fri - 9:00 AM - 2:30 PM tomorrow - now + 10 minutes .. note:: If you pass a time only, with no 'AM/PM' designation, you have to double quote the parameter on the command line. For example: '"14:00"' CLI Example: .. code-block:: bash salt '*' system.halt salt '*' system.halt 'now + 10 minutes' ''' cmd = 'shutdown -h now' return _execute_command(cmd, at_time) def sleep(at_time=None): ''' Sleep the system. If a user is active on the system it will likely fail to sleep. :param str at_time: Any valid `at` expression. For example, some valid at expressions could be: - noon - midnight - fri - 9:00 AM - 2:30 PM tomorrow - now + 10 minutes .. note:: If you pass a time only, with no 'AM/PM' designation, you have to double quote the parameter on the command line. For example: '"14:00"' CLI Example: .. code-block:: bash salt '*' system.sleep salt '*' system.sleep '10:00 PM' ''' cmd = 'shutdown -s now' return _execute_command(cmd, at_time) def restart(at_time=None): ''' Restart the system :param str at_time: Any valid `at` expression. For example, some valid at expressions could be: - noon - midnight - fri - 9:00 AM - 2:30 PM tomorrow - now + 10 minutes .. note:: If you pass a time only, with no 'AM/PM' designation, you have to double quote the parameter on the command line. For example: '"14:00"' CLI Example: .. code-block:: bash salt '*' system.restart salt '*' system.restart '12:00 PM fri' ''' cmd = 'shutdown -r now' return _execute_command(cmd, at_time) def shutdown(at_time=None): ''' Shutdown the system :param str at_time: Any valid `at` expression. For example, some valid at expressions could be: - noon - midnight - fri - 9:00 AM - 2:30 PM tomorrow - now + 10 minutes .. note:: If you pass a time only, with no 'AM/PM' designation, you have to double quote the parameter on the command line. For example: '"14:00"' CLI Example: .. code-block:: bash salt '*' system.shutdown salt '*' system.shutdown 'now + 1 hour' ''' return halt(at_time) def get_remote_login(): ''' Displays whether remote login (SSH) is on or off. :return: True if remote login is on, False if off :rtype: bool CLI Example: .. code-block:: bash salt '*' system.get_remote_login ''' ret = __utils__['mac_utils.execute_return_result']( 'systemsetup -getremotelogin') enabled = __utils__['mac_utils.validate_enabled']( __utils__['mac_utils.parse_return'](ret)) return enabled == 'on' def set_remote_login(enable): ''' Set the remote login (SSH) to either on or off. :param bool enable: True to enable, False to disable. "On" and "Off" are also acceptable values. Additionally you can pass 1 and 0 to represent True and False respectively :return: True if successful, False if not :rtype: bool CLI Example: .. code-block:: bash salt '*' system.set_remote_login True ''' state = __utils__['mac_utils.validate_enabled'](enable) cmd = 'systemsetup -f -setremotelogin {0}'.format(state) __utils__['mac_utils.execute_return_success'](cmd) return __utils__['mac_utils.confirm_updated'](state, get_remote_login, normalize_ret=True) def get_remote_events(): ''' Displays whether remote apple events are on or off. :return: True if remote apple events are on, False if off :rtype: bool CLI Example: .. code-block:: bash salt '*' system.get_remote_events ''' ret = __utils__['mac_utils.execute_return_result']( 'systemsetup -getremoteappleevents') enabled = __utils__['mac_utils.validate_enabled']( __utils__['mac_utils.parse_return'](ret)) return enabled == 'on' def set_remote_events(enable): ''' Set whether the server responds to events sent by other computers (such as AppleScripts) :param bool enable: True to enable, False to disable. "On" and "Off" are also acceptable values. Additionally you can pass 1 and 0 to represent True and False respectively :return: True if successful, False if not :rtype: bool CLI Example: .. code-block:: bash salt '*' system.set_remote_events On ''' state = __utils__['mac_utils.validate_enabled'](enable) cmd = 'systemsetup -setremoteappleevents {0}'.format(state) __utils__['mac_utils.execute_return_success'](cmd) return __utils__['mac_utils.confirm_updated']( state, get_remote_events, normalize_ret=True, ) def get_computer_name(): ''' Gets the computer name :return: The computer name :rtype: str CLI Example: .. code-block:: bash salt '*' system.get_computer_name ''' ret = __utils__['mac_utils.execute_return_result']( 'systemsetup -getcomputername') return __utils__['mac_utils.parse_return'](ret) def set_computer_name(name): ''' Set the computer name :param str name: The new computer name :return: True if successful, False if not :rtype: bool CLI Example: .. code-block:: bash salt '*' system.set_computer_name "Mike's Mac" ''' cmd = 'systemsetup -setcomputername "{0}"'.format(name) __utils__['mac_utils.execute_return_success'](cmd) return __utils__['mac_utils.confirm_updated']( name, get_computer_name, ) def get_subnet_name(): ''' Gets the local subnet name :return: The local subnet name :rtype: str CLI Example: .. code-block:: bash salt '*' system.get_subnet_name ''' ret = __utils__['mac_utils.execute_return_result']( 'systemsetup -getlocalsubnetname') return __utils__['mac_utils.parse_return'](ret) def set_subnet_name(name): ''' Set the local subnet name :param str name: The new local subnet name .. note:: Spaces are changed to dashes. Other special characters are removed. :return: True if successful, False if not :rtype: bool CLI Example: .. code-block:: bash The following will be set as 'Mikes-Mac' salt '*' system.set_subnet_name "Mike's Mac" ''' cmd = 'systemsetup -setlocalsubnetname "{0}"'.format(name) __utils__['mac_utils.execute_return_success'](cmd) return __utils__['mac_utils.confirm_updated']( name, get_subnet_name, ) def get_startup_disk(): ''' Displays the current startup disk :return: The current startup disk :rtype: str CLI Example: .. code-block:: bash salt '*' system.get_startup_disk ''' ret = __utils__['mac_utils.execute_return_result']( 'systemsetup -getstartupdisk') return __utils__['mac_utils.parse_return'](ret) def list_startup_disks(): ''' List all valid startup disks on the system. :return: A list of valid startup disks :rtype: list CLI Example: .. code-block:: bash salt '*' system.list_startup_disks ''' ret = __utils__['mac_utils.execute_return_result']( 'systemsetup -liststartupdisks') return ret.splitlines() def set_startup_disk(path): ''' Set the current startup disk to the indicated path. Use ``system.list_startup_disks`` to find valid startup disks on the system. :param str path: The valid startup disk path :return: True if successful, False if not :rtype: bool CLI Example: .. code-block:: bash salt '*' system.set_startup_disk /System/Library/CoreServices ''' if path not in list_startup_disks(): msg = 'Invalid value passed for path.\n' \ 'Must be a valid startup disk as found in ' \ 'system.list_startup_disks.\n' \ 'Passed: {0}'.format(path) raise SaltInvocationError(msg) cmd = 'systemsetup -setstartupdisk {0}'.format(path) __utils__['mac_utils.execute_return_result'](cmd) return __utils__['mac_utils.confirm_updated']( path, get_startup_disk, ) def get_restart_delay(): ''' Get the number of seconds after which the computer will start up after a power failure. :return: A string value representing the number of seconds the system will delay restart after power loss :rtype: str CLI Example: .. code-block:: bash salt '*' system.get_restart_delay ''' ret = __utils__['mac_utils.execute_return_result']( 'systemsetup -getwaitforstartupafterpowerfailure') return __utils__['mac_utils.parse_return'](ret) def set_restart_delay(seconds): ''' Set the number of seconds after which the computer will start up after a power failure. .. warning:: This command fails with the following error: ``Error, IOServiceOpen returned 0x10000003`` The setting is not updated. This is an apple bug. It seems like it may only work on certain versions of Mac Server X. This article explains the issue in more detail, though it is quite old. http://lists.apple.com/archives/macos-x-server/2006/Jul/msg00967.html :param int seconds: The number of seconds. Must be a multiple of 30 :return: True if successful, False if not :rtype: bool CLI Example: .. code-block:: bash salt '*' system.set_restart_delay 180 ''' if seconds % 30 != 0: msg = 'Invalid value passed for seconds.\n' \ 'Must be a multiple of 30.\n' \ 'Passed: {0}'.format(seconds) raise SaltInvocationError(msg) cmd = 'systemsetup -setwaitforstartupafterpowerfailure {0}'.format(seconds) __utils__['mac_utils.execute_return_success'](cmd) return __utils__['mac_utils.confirm_updated']( seconds, get_restart_delay, ) def get_disable_keyboard_on_lock(): ''' Get whether or not the keyboard should be disabled when the X Serve enclosure lock is engaged. :return: True if disable keyboard on lock is on, False if off :rtype: bool CLI Example: ..code-block:: bash salt '*' system.get_disable_keyboard_on_lock ''' ret = __utils__['mac_utils.execute_return_result']( 'systemsetup -getdisablekeyboardwhenenclosurelockisengaged') enabled = __utils__['mac_utils.validate_enabled']( __utils__['mac_utils.parse_return'](ret)) return enabled == 'on' def get_boot_arch(): ''' Get the kernel architecture setting from ``com.apple.Boot.plist`` :return: A string value representing the boot architecture setting :rtype: str CLI Example: .. code-block:: bash salt '*' system.get_boot_arch ''' ret = __utils__['mac_utils.execute_return_result']( 'systemsetup -getkernelbootarchitecturesetting') arch = __utils__['mac_utils.parse_return'](ret) if 'default' in arch: return 'default' elif 'i386' in arch: return 'i386' elif 'x86_64' in arch: return 'x86_64' return 'unknown' def set_boot_arch(arch='default'): ''' Set the kernel to boot in 32 or 64 bit mode on next boot. .. note:: When this function fails with the error ``changes to kernel architecture failed to save!``, then the boot arch is not updated. This is either an Apple bug, not available on the test system, or a result of system files being locked down in macOS (SIP Protection). :param str arch: A string representing the desired architecture. If no value is passed, default is assumed. Valid values include: - i386 - x86_64 - default :return: True if successful, False if not :rtype: bool CLI Example: .. code-block:: bash salt '*' system.set_boot_arch i386 ''' if arch not in ['i386', 'x86_64', 'default']: msg = 'Invalid value passed for arch.\n' \ 'Must be i386, x86_64, or default.\n' \ 'Passed: {0}'.format(arch) raise SaltInvocationError(msg) cmd = 'systemsetup -setkernelbootarchitecture {0}'.format(arch) __utils__['mac_utils.execute_return_success'](cmd) return __utils__['mac_utils.confirm_updated']( arch, get_boot_arch, )
saltstack/salt
salt/modules/mac_system.py
set_boot_arch
python
def set_boot_arch(arch='default'): ''' Set the kernel to boot in 32 or 64 bit mode on next boot. .. note:: When this function fails with the error ``changes to kernel architecture failed to save!``, then the boot arch is not updated. This is either an Apple bug, not available on the test system, or a result of system files being locked down in macOS (SIP Protection). :param str arch: A string representing the desired architecture. If no value is passed, default is assumed. Valid values include: - i386 - x86_64 - default :return: True if successful, False if not :rtype: bool CLI Example: .. code-block:: bash salt '*' system.set_boot_arch i386 ''' if arch not in ['i386', 'x86_64', 'default']: msg = 'Invalid value passed for arch.\n' \ 'Must be i386, x86_64, or default.\n' \ 'Passed: {0}'.format(arch) raise SaltInvocationError(msg) cmd = 'systemsetup -setkernelbootarchitecture {0}'.format(arch) __utils__['mac_utils.execute_return_success'](cmd) return __utils__['mac_utils.confirm_updated']( arch, get_boot_arch, )
Set the kernel to boot in 32 or 64 bit mode on next boot. .. note:: When this function fails with the error ``changes to kernel architecture failed to save!``, then the boot arch is not updated. This is either an Apple bug, not available on the test system, or a result of system files being locked down in macOS (SIP Protection). :param str arch: A string representing the desired architecture. If no value is passed, default is assumed. Valid values include: - i386 - x86_64 - default :return: True if successful, False if not :rtype: bool CLI Example: .. code-block:: bash salt '*' system.set_boot_arch i386
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/mac_system.py#L606-L644
null
# -*- coding: utf-8 -*- ''' System module for sleeping, restarting, and shutting down the system on Mac OS X .. versionadded:: 2016.3.0 .. warning:: Using this module will enable ``atrun`` on the system if it is disabled. ''' from __future__ import absolute_import, unicode_literals, print_function # Import python libs try: # python 3 from shlex import quote as _cmd_quote # pylint: disable=E0611 except ImportError: # python 2 from pipes import quote as _cmd_quote import getpass # Import salt libs import salt.utils.platform from salt.exceptions import SaltInvocationError, CommandExecutionError __virtualname__ = 'system' def __virtual__(): ''' Only for MacOS with atrun enabled ''' if not salt.utils.platform.is_darwin(): return (False, 'The mac_system module could not be loaded: ' 'module only works on MacOS systems.') if getpass.getuser() != 'root': return False, 'The mac_system module is not useful for non-root users.' if not _atrun_enabled(): if not _enable_atrun(): return False, 'atrun could not be enabled on this system' return __virtualname__ def _atrun_enabled(): ''' Check to see if atrun is running and enabled on the system ''' try: return __salt__['service.list']('com.apple.atrun') except CommandExecutionError: return False def _enable_atrun(): ''' Enable and start the atrun daemon ''' name = 'com.apple.atrun' try: __salt__['service.enable'](name) __salt__['service.start'](name) except CommandExecutionError: return False return _atrun_enabled() def _execute_command(cmd, at_time=None): ''' Helper function to execute the command :param str cmd: the command to run :param str at_time: If passed, the cmd will be scheduled. Returns: bool ''' if at_time: cmd = 'echo \'{0}\' | at {1}'.format(cmd, _cmd_quote(at_time)) return not bool(__salt__['cmd.retcode'](cmd, python_shell=True)) def halt(at_time=None): ''' Halt a running system :param str at_time: Any valid `at` expression. For example, some valid at expressions could be: - noon - midnight - fri - 9:00 AM - 2:30 PM tomorrow - now + 10 minutes .. note:: If you pass a time only, with no 'AM/PM' designation, you have to double quote the parameter on the command line. For example: '"14:00"' CLI Example: .. code-block:: bash salt '*' system.halt salt '*' system.halt 'now + 10 minutes' ''' cmd = 'shutdown -h now' return _execute_command(cmd, at_time) def sleep(at_time=None): ''' Sleep the system. If a user is active on the system it will likely fail to sleep. :param str at_time: Any valid `at` expression. For example, some valid at expressions could be: - noon - midnight - fri - 9:00 AM - 2:30 PM tomorrow - now + 10 minutes .. note:: If you pass a time only, with no 'AM/PM' designation, you have to double quote the parameter on the command line. For example: '"14:00"' CLI Example: .. code-block:: bash salt '*' system.sleep salt '*' system.sleep '10:00 PM' ''' cmd = 'shutdown -s now' return _execute_command(cmd, at_time) def restart(at_time=None): ''' Restart the system :param str at_time: Any valid `at` expression. For example, some valid at expressions could be: - noon - midnight - fri - 9:00 AM - 2:30 PM tomorrow - now + 10 minutes .. note:: If you pass a time only, with no 'AM/PM' designation, you have to double quote the parameter on the command line. For example: '"14:00"' CLI Example: .. code-block:: bash salt '*' system.restart salt '*' system.restart '12:00 PM fri' ''' cmd = 'shutdown -r now' return _execute_command(cmd, at_time) def shutdown(at_time=None): ''' Shutdown the system :param str at_time: Any valid `at` expression. For example, some valid at expressions could be: - noon - midnight - fri - 9:00 AM - 2:30 PM tomorrow - now + 10 minutes .. note:: If you pass a time only, with no 'AM/PM' designation, you have to double quote the parameter on the command line. For example: '"14:00"' CLI Example: .. code-block:: bash salt '*' system.shutdown salt '*' system.shutdown 'now + 1 hour' ''' return halt(at_time) def get_remote_login(): ''' Displays whether remote login (SSH) is on or off. :return: True if remote login is on, False if off :rtype: bool CLI Example: .. code-block:: bash salt '*' system.get_remote_login ''' ret = __utils__['mac_utils.execute_return_result']( 'systemsetup -getremotelogin') enabled = __utils__['mac_utils.validate_enabled']( __utils__['mac_utils.parse_return'](ret)) return enabled == 'on' def set_remote_login(enable): ''' Set the remote login (SSH) to either on or off. :param bool enable: True to enable, False to disable. "On" and "Off" are also acceptable values. Additionally you can pass 1 and 0 to represent True and False respectively :return: True if successful, False if not :rtype: bool CLI Example: .. code-block:: bash salt '*' system.set_remote_login True ''' state = __utils__['mac_utils.validate_enabled'](enable) cmd = 'systemsetup -f -setremotelogin {0}'.format(state) __utils__['mac_utils.execute_return_success'](cmd) return __utils__['mac_utils.confirm_updated'](state, get_remote_login, normalize_ret=True) def get_remote_events(): ''' Displays whether remote apple events are on or off. :return: True if remote apple events are on, False if off :rtype: bool CLI Example: .. code-block:: bash salt '*' system.get_remote_events ''' ret = __utils__['mac_utils.execute_return_result']( 'systemsetup -getremoteappleevents') enabled = __utils__['mac_utils.validate_enabled']( __utils__['mac_utils.parse_return'](ret)) return enabled == 'on' def set_remote_events(enable): ''' Set whether the server responds to events sent by other computers (such as AppleScripts) :param bool enable: True to enable, False to disable. "On" and "Off" are also acceptable values. Additionally you can pass 1 and 0 to represent True and False respectively :return: True if successful, False if not :rtype: bool CLI Example: .. code-block:: bash salt '*' system.set_remote_events On ''' state = __utils__['mac_utils.validate_enabled'](enable) cmd = 'systemsetup -setremoteappleevents {0}'.format(state) __utils__['mac_utils.execute_return_success'](cmd) return __utils__['mac_utils.confirm_updated']( state, get_remote_events, normalize_ret=True, ) def get_computer_name(): ''' Gets the computer name :return: The computer name :rtype: str CLI Example: .. code-block:: bash salt '*' system.get_computer_name ''' ret = __utils__['mac_utils.execute_return_result']( 'systemsetup -getcomputername') return __utils__['mac_utils.parse_return'](ret) def set_computer_name(name): ''' Set the computer name :param str name: The new computer name :return: True if successful, False if not :rtype: bool CLI Example: .. code-block:: bash salt '*' system.set_computer_name "Mike's Mac" ''' cmd = 'systemsetup -setcomputername "{0}"'.format(name) __utils__['mac_utils.execute_return_success'](cmd) return __utils__['mac_utils.confirm_updated']( name, get_computer_name, ) def get_subnet_name(): ''' Gets the local subnet name :return: The local subnet name :rtype: str CLI Example: .. code-block:: bash salt '*' system.get_subnet_name ''' ret = __utils__['mac_utils.execute_return_result']( 'systemsetup -getlocalsubnetname') return __utils__['mac_utils.parse_return'](ret) def set_subnet_name(name): ''' Set the local subnet name :param str name: The new local subnet name .. note:: Spaces are changed to dashes. Other special characters are removed. :return: True if successful, False if not :rtype: bool CLI Example: .. code-block:: bash The following will be set as 'Mikes-Mac' salt '*' system.set_subnet_name "Mike's Mac" ''' cmd = 'systemsetup -setlocalsubnetname "{0}"'.format(name) __utils__['mac_utils.execute_return_success'](cmd) return __utils__['mac_utils.confirm_updated']( name, get_subnet_name, ) def get_startup_disk(): ''' Displays the current startup disk :return: The current startup disk :rtype: str CLI Example: .. code-block:: bash salt '*' system.get_startup_disk ''' ret = __utils__['mac_utils.execute_return_result']( 'systemsetup -getstartupdisk') return __utils__['mac_utils.parse_return'](ret) def list_startup_disks(): ''' List all valid startup disks on the system. :return: A list of valid startup disks :rtype: list CLI Example: .. code-block:: bash salt '*' system.list_startup_disks ''' ret = __utils__['mac_utils.execute_return_result']( 'systemsetup -liststartupdisks') return ret.splitlines() def set_startup_disk(path): ''' Set the current startup disk to the indicated path. Use ``system.list_startup_disks`` to find valid startup disks on the system. :param str path: The valid startup disk path :return: True if successful, False if not :rtype: bool CLI Example: .. code-block:: bash salt '*' system.set_startup_disk /System/Library/CoreServices ''' if path not in list_startup_disks(): msg = 'Invalid value passed for path.\n' \ 'Must be a valid startup disk as found in ' \ 'system.list_startup_disks.\n' \ 'Passed: {0}'.format(path) raise SaltInvocationError(msg) cmd = 'systemsetup -setstartupdisk {0}'.format(path) __utils__['mac_utils.execute_return_result'](cmd) return __utils__['mac_utils.confirm_updated']( path, get_startup_disk, ) def get_restart_delay(): ''' Get the number of seconds after which the computer will start up after a power failure. :return: A string value representing the number of seconds the system will delay restart after power loss :rtype: str CLI Example: .. code-block:: bash salt '*' system.get_restart_delay ''' ret = __utils__['mac_utils.execute_return_result']( 'systemsetup -getwaitforstartupafterpowerfailure') return __utils__['mac_utils.parse_return'](ret) def set_restart_delay(seconds): ''' Set the number of seconds after which the computer will start up after a power failure. .. warning:: This command fails with the following error: ``Error, IOServiceOpen returned 0x10000003`` The setting is not updated. This is an apple bug. It seems like it may only work on certain versions of Mac Server X. This article explains the issue in more detail, though it is quite old. http://lists.apple.com/archives/macos-x-server/2006/Jul/msg00967.html :param int seconds: The number of seconds. Must be a multiple of 30 :return: True if successful, False if not :rtype: bool CLI Example: .. code-block:: bash salt '*' system.set_restart_delay 180 ''' if seconds % 30 != 0: msg = 'Invalid value passed for seconds.\n' \ 'Must be a multiple of 30.\n' \ 'Passed: {0}'.format(seconds) raise SaltInvocationError(msg) cmd = 'systemsetup -setwaitforstartupafterpowerfailure {0}'.format(seconds) __utils__['mac_utils.execute_return_success'](cmd) return __utils__['mac_utils.confirm_updated']( seconds, get_restart_delay, ) def get_disable_keyboard_on_lock(): ''' Get whether or not the keyboard should be disabled when the X Serve enclosure lock is engaged. :return: True if disable keyboard on lock is on, False if off :rtype: bool CLI Example: ..code-block:: bash salt '*' system.get_disable_keyboard_on_lock ''' ret = __utils__['mac_utils.execute_return_result']( 'systemsetup -getdisablekeyboardwhenenclosurelockisengaged') enabled = __utils__['mac_utils.validate_enabled']( __utils__['mac_utils.parse_return'](ret)) return enabled == 'on' def set_disable_keyboard_on_lock(enable): ''' Get whether or not the keyboard should be disabled when the X Serve enclosure lock is engaged. :param bool enable: True to enable, False to disable. "On" and "Off" are also acceptable values. Additionally you can pass 1 and 0 to represent True and False respectively :return: True if successful, False if not :rtype: bool CLI Example: .. code-block:: bash salt '*' system.set_disable_keyboard_on_lock False ''' state = __utils__['mac_utils.validate_enabled'](enable) cmd = 'systemsetup -setdisablekeyboardwhenenclosurelockisengaged ' \ '{0}'.format(state) __utils__['mac_utils.execute_return_success'](cmd) return __utils__['mac_utils.confirm_updated']( state, get_disable_keyboard_on_lock, normalize_ret=True, ) def get_boot_arch(): ''' Get the kernel architecture setting from ``com.apple.Boot.plist`` :return: A string value representing the boot architecture setting :rtype: str CLI Example: .. code-block:: bash salt '*' system.get_boot_arch ''' ret = __utils__['mac_utils.execute_return_result']( 'systemsetup -getkernelbootarchitecturesetting') arch = __utils__['mac_utils.parse_return'](ret) if 'default' in arch: return 'default' elif 'i386' in arch: return 'i386' elif 'x86_64' in arch: return 'x86_64' return 'unknown'
saltstack/salt
salt/modules/boto_elbv2.py
create_target_group
python
def create_target_group(name, protocol, port, vpc_id, region=None, key=None, keyid=None, profile=None, health_check_protocol='HTTP', health_check_port='traffic-port', health_check_path='/', health_check_interval_seconds=30, health_check_timeout_seconds=5, healthy_threshold_count=5, unhealthy_threshold_count=2): ''' Create target group if not present. name (string) - The name of the target group. protocol (string) - The protocol to use for routing traffic to the targets port (int) - The port on which the targets receive traffic. This port is used unless you specify a port override when registering the traffic. vpc_id (string) - The identifier of the virtual private cloud (VPC). health_check_protocol (string) - The protocol the load balancer uses when performing health check on targets. The default is the HTTP protocol. health_check_port (string) - The port the load balancer uses when performing health checks on targets. The default is 'traffic-port', which indicates the port on which each target receives traffic from the load balancer. health_check_path (string) - The ping path that is the destination on the targets for health checks. The default is /. health_check_interval_seconds (integer) - The approximate amount of time, in seconds, between health checks of an individual target. The default is 30 seconds. health_check_timeout_seconds (integer) - The amount of time, in seconds, during which no response from a target means a failed health check. The default is 5 seconds. healthy_threshold_count (integer) - The number of consecutive health checks successes required before considering an unhealthy target healthy. The default is 5. unhealthy_threshold_count (integer) - The number of consecutive health check failures required before considering a target unhealthy. The default is 2. returns (bool) - True on success, False on failure. CLI example: .. code-block:: bash salt myminion boto_elbv2.create_target_group learn1give1 protocol=HTTP port=54006 vpc_id=vpc-deadbeef ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if target_group_exists(name, region, key, keyid, profile): return True try: alb = conn.create_target_group(Name=name, Protocol=protocol, Port=port, VpcId=vpc_id, HealthCheckProtocol=health_check_protocol, HealthCheckPort=health_check_port, HealthCheckPath=health_check_path, HealthCheckIntervalSeconds=health_check_interval_seconds, HealthCheckTimeoutSeconds=health_check_timeout_seconds, HealthyThresholdCount=healthy_threshold_count, UnhealthyThresholdCount=unhealthy_threshold_count) if alb: log.info('Created ALB %s: %s', name, alb['TargetGroups'][0]['TargetGroupArn']) return True else: log.error('Failed to create ALB %s', name) return False except ClientError as error: log.error( 'Failed to create ALB %s: %s: %s', name, error.response['Error']['Code'], error.response['Error']['Message'], exc_info_on_loglevel=logging.DEBUG )
Create target group if not present. name (string) - The name of the target group. protocol (string) - The protocol to use for routing traffic to the targets port (int) - The port on which the targets receive traffic. This port is used unless you specify a port override when registering the traffic. vpc_id (string) - The identifier of the virtual private cloud (VPC). health_check_protocol (string) - The protocol the load balancer uses when performing health check on targets. The default is the HTTP protocol. health_check_port (string) - The port the load balancer uses when performing health checks on targets. The default is 'traffic-port', which indicates the port on which each target receives traffic from the load balancer. health_check_path (string) - The ping path that is the destination on the targets for health checks. The default is /. health_check_interval_seconds (integer) - The approximate amount of time, in seconds, between health checks of an individual target. The default is 30 seconds. health_check_timeout_seconds (integer) - The amount of time, in seconds, during which no response from a target means a failed health check. The default is 5 seconds. healthy_threshold_count (integer) - The number of consecutive health checks successes required before considering an unhealthy target healthy. The default is 5. unhealthy_threshold_count (integer) - The number of consecutive health check failures required before considering a target unhealthy. The default is 2. returns (bool) - True on success, False on failure. CLI example: .. code-block:: bash salt myminion boto_elbv2.create_target_group learn1give1 protocol=HTTP port=54006 vpc_id=vpc-deadbeef
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_elbv2.py#L79-L163
[ "def target_group_exists(name,\n region=None,\n key=None,\n keyid=None,\n profile=None):\n '''\n Check to see if an target group exists.\n\n CLI example:\n\n .. code-block:: bash\n\n salt myminion boto_elbv2.target_group_exists arn:aws:elasticloadbalancing:us-west-2:644138682826:targetgroup/learn1give1-api/414788a16b5cf163\n '''\n conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)\n\n try:\n if name.startswith('arn:aws:elasticloadbalancing'):\n alb = conn.describe_target_groups(TargetGroupArns=[name])\n else:\n alb = conn.describe_target_groups(Names=[name])\n if alb:\n return True\n else:\n log.warning('The target group does not exist in region %s', region)\n return False\n except ClientError as error:\n log.warning('target_group_exists check for %s returned: %s', name, error)\n return False\n" ]
# -*- coding: utf-8 -*- ''' Connection module for Amazon ALB .. versionadded:: 2017.7.0 :configuration: This module accepts explicit elb credentials but can also utilize IAM roles assigned to the instance through Instance Profiles. Dynamic credentials are then automatically obtained from AWS API and no further configuration is necessary. More Information available at: .. code-block:: text http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/iam-roles-for-amazon-ec2.html If IAM roles are not used you need to specify them either in a pillar or in the minion's config file: .. code-block:: yaml elbv2.keyid: GKTADJGHEIQSXMKKRBJ08H elbv2.key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs elbv2.region: us-west-2 If a region is not specified, the default is us-east-1. It's also possible to specify key, keyid and region via a profile, either as a passed in dict, or as a string to pull from pillars or minion config: .. code-block:: yaml myprofile: keyid: GKTADJGHEIQSXMKKRBJ08H key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs region: us-east-1 :depends: boto3 ''' # keep lint from choking on _get_conn and _cache_id # pylint: disable=E0602 from __future__ import absolute_import, print_function, unicode_literals # Import Python libs import logging log = logging.getLogger(__name__) # Import Salt libs from salt.ext import six import salt.utils.versions # Import third-party libs try: # pylint: disable=unused-import import boto3 import botocore # pylint: enable=unused-import # TODO Version check using salt.utils.versions from botocore.exceptions import ClientError logging.getLogger('boto3').setLevel(logging.CRITICAL) HAS_BOTO = True except ImportError: HAS_BOTO = False def __virtual__(): ''' Only load if boto3 libraries exist. ''' has_boto_reqs = salt.utils.versions.check_boto_reqs() if has_boto_reqs is True: __utils__['boto3.assign_funcs'](__name__, 'elbv2') return has_boto_reqs def delete_target_group(name, region=None, key=None, keyid=None, profile=None): ''' Delete target group. name (string) - Target Group Name or Amazon Resource Name (ARN). returns (bool) - True on success, False on failure. CLI example: .. code-block:: bash salt myminion boto_elbv2.delete_target_group arn:aws:elasticloadbalancing:us-west-2:644138682826:targetgroup/learn1give1-api/414788a16b5cf163 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not target_group_exists(name, region, key, keyid, profile): return True try: if name.startswith('arn:aws:elasticloadbalancing'): conn.delete_target_group(TargetGroupArn=name) log.info('Deleted target group %s', name) else: tg_info = conn.describe_target_groups(Names=[name]) if len(tg_info['TargetGroups']) != 1: return False arn = tg_info['TargetGroups'][0]['TargetGroupArn'] conn.delete_target_group(TargetGroupArn=arn) log.info('Deleted target group %s ARN %s', name, arn) return True except ClientError as error: log.error('Failed to delete target group %s', name, exc_info_on_loglevel=logging.DEBUG) return False def target_group_exists(name, region=None, key=None, keyid=None, profile=None): ''' Check to see if an target group exists. CLI example: .. code-block:: bash salt myminion boto_elbv2.target_group_exists arn:aws:elasticloadbalancing:us-west-2:644138682826:targetgroup/learn1give1-api/414788a16b5cf163 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: if name.startswith('arn:aws:elasticloadbalancing'): alb = conn.describe_target_groups(TargetGroupArns=[name]) else: alb = conn.describe_target_groups(Names=[name]) if alb: return True else: log.warning('The target group does not exist in region %s', region) return False except ClientError as error: log.warning('target_group_exists check for %s returned: %s', name, error) return False def describe_target_health(name, targets=None, region=None, key=None, keyid=None, profile=None): ''' Get the curret health check status for targets in a target group. CLI example: .. code-block:: bash salt myminion boto_elbv2.describe_target_health arn:aws:elasticloadbalancing:us-west-2:644138682826:targetgroup/learn1give1-api/414788a16b5cf163 targets=["i-isdf23ifjf"] ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: if targets: targetsdict = [] for target in targets: targetsdict.append({"Id": target}) instances = conn.describe_target_health(TargetGroupArn=name, Targets=targetsdict) else: instances = conn.describe_target_health(TargetGroupArn=name) ret = {} for instance in instances['TargetHealthDescriptions']: ret.update({instance['Target']['Id']: instance['TargetHealth']['State']}) return ret except ClientError as error: log.warning(error) return {} def register_targets(name, targets, region=None, key=None, keyid=None, profile=None): ''' Register targets to a target froup of an ALB. ``targets`` is either a instance id string or a list of instance id's. Returns: - ``True``: instance(s) registered successfully - ``False``: instance(s) failed to be registered CLI example: .. code-block:: bash salt myminion boto_elbv2.register_targets myelb instance_id salt myminion boto_elbv2.register_targets myelb "[instance_id,instance_id]" ''' targetsdict = [] if isinstance(targets, six.string_types) or isinstance(targets, six.text_type): targetsdict.append({"Id": targets}) else: for target in targets: targetsdict.append({"Id": target}) conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: registered_targets = conn.register_targets(TargetGroupArn=name, Targets=targetsdict) if registered_targets: return True return False except ClientError as error: log.warning(error) return False def deregister_targets(name, targets, region=None, key=None, keyid=None, profile=None): ''' Deregister targets to a target froup of an ALB. ``targets`` is either a instance id string or a list of instance id's. Returns: - ``True``: instance(s) deregistered successfully - ``False``: instance(s) failed to be deregistered CLI example: .. code-block:: bash salt myminion boto_elbv2.deregister_targets myelb instance_id salt myminion boto_elbv2.deregister_targets myelb "[instance_id,instance_id]" ''' targetsdict = [] if isinstance(targets, six.string_types) or isinstance(targets, six.text_type): targetsdict.append({"Id": targets}) else: for target in targets: targetsdict.append({"Id": target}) conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: registered_targets = conn.deregister_targets(TargetGroupArn=name, Targets=targetsdict) if registered_targets: return True return False except ClientError as error: log.warning(error) return False def describe_load_balancers(names=None, load_balancer_arns=None, region=None, key=None, keyid=None, profile=None): ''' Describes the specified load balancer or all of your load balancers. Returns: list CLI example: .. code-block:: bash salt myminion boto_elbv2.describe_load_balancers salt myminion boto_elbv2.describe_load_balancers alb_name salt myminion boto_elbv2.describe_load_balancers "[alb_name,alb_name]" ''' if names and load_balancer_arns: raise SaltInvocationError('At most one of names or load_balancer_arns may ' 'be provided') if names: albs = names elif load_balancer_arns: albs = load_balancer_arns else: albs = None albs_list = [] if albs: if isinstance(albs, str) or isinstance(albs, six.text_type): albs_list.append(albs) else: for alb in albs: albs_list.append(alb) conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: if names: ret = conn.describe_load_balancers(Names=albs_list)['LoadBalancers'] elif load_balancer_arns: ret = conn.describe_load_balancers(LoadBalancerArns=albs_list)['LoadBalancers'] else: ret = [] next_marker = '' while True: r = conn.describe_load_balancers(Marker=next_marker) for alb in r['LoadBalancers']: ret.append(alb) if 'NextMarker' in r: next_marker = r['NextMarker'] else: break return ret if ret else [] except ClientError as error: log.warning(error) return False def describe_target_groups(names=None, target_group_arns=None, load_balancer_arn=None, region=None, key=None, keyid=None, profile=None): ''' Describes the specified target groups or all of your target groups. By default, all target groups are described. Alternatively, you can specify one of the following to filter the results: the ARN of the load balancer, the names of one or more target groups, or the ARNs of one or more target groups. Returns: list CLI example: .. code-block:: bash salt myminion boto_elbv2.describe_target_groups salt myminion boto_elbv2.describe_target_groups target_group_name salt myminion boto_elbv2.describe_target_groups "[tg_name,tg_name]" ''' if names and target_group_arns: raise SaltInvocationError('At most one of names or target_group_arns may ' 'be provided') if names: target_groups = names elif target_group_arns: target_groups = target_group_arns else: target_groups = None tg_list = [] if target_groups: if isinstance(target_groups, str) or isinstance(target_groups, six.text_type): tg_list.append(target_groups) else: for group in target_groups: tg_list.append(group) conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: if names: ret = conn.describe_target_groups(Names=tg_list)['TargetGroups'] elif target_group_arns: ret = conn.describe_target_groups(TargetGroupArns=tg_list)['TargetGroups'] elif load_balancer_arn: ret = conn.describe_target_groups(LoadBalancerArn=load_balancer_arn)['TargetGroups'] else: ret = [] next_marker = '' while True: r = conn.describe_target_groups(Marker=next_marker) for alb in r['TargetGroups']: ret.append(alb) if 'NextMarker' in r: next_marker = r['NextMarker'] else: break return ret if ret else [] except ClientError as error: log.warning(error) return False
saltstack/salt
salt/modules/boto_elbv2.py
delete_target_group
python
def delete_target_group(name, region=None, key=None, keyid=None, profile=None): ''' Delete target group. name (string) - Target Group Name or Amazon Resource Name (ARN). returns (bool) - True on success, False on failure. CLI example: .. code-block:: bash salt myminion boto_elbv2.delete_target_group arn:aws:elasticloadbalancing:us-west-2:644138682826:targetgroup/learn1give1-api/414788a16b5cf163 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not target_group_exists(name, region, key, keyid, profile): return True try: if name.startswith('arn:aws:elasticloadbalancing'): conn.delete_target_group(TargetGroupArn=name) log.info('Deleted target group %s', name) else: tg_info = conn.describe_target_groups(Names=[name]) if len(tg_info['TargetGroups']) != 1: return False arn = tg_info['TargetGroups'][0]['TargetGroupArn'] conn.delete_target_group(TargetGroupArn=arn) log.info('Deleted target group %s ARN %s', name, arn) return True except ClientError as error: log.error('Failed to delete target group %s', name, exc_info_on_loglevel=logging.DEBUG) return False
Delete target group. name (string) - Target Group Name or Amazon Resource Name (ARN). returns (bool) - True on success, False on failure. CLI example: .. code-block:: bash salt myminion boto_elbv2.delete_target_group arn:aws:elasticloadbalancing:us-west-2:644138682826:targetgroup/learn1give1-api/414788a16b5cf163
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_elbv2.py#L166-L206
[ "def target_group_exists(name,\n region=None,\n key=None,\n keyid=None,\n profile=None):\n '''\n Check to see if an target group exists.\n\n CLI example:\n\n .. code-block:: bash\n\n salt myminion boto_elbv2.target_group_exists arn:aws:elasticloadbalancing:us-west-2:644138682826:targetgroup/learn1give1-api/414788a16b5cf163\n '''\n conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)\n\n try:\n if name.startswith('arn:aws:elasticloadbalancing'):\n alb = conn.describe_target_groups(TargetGroupArns=[name])\n else:\n alb = conn.describe_target_groups(Names=[name])\n if alb:\n return True\n else:\n log.warning('The target group does not exist in region %s', region)\n return False\n except ClientError as error:\n log.warning('target_group_exists check for %s returned: %s', name, error)\n return False\n" ]
# -*- coding: utf-8 -*- ''' Connection module for Amazon ALB .. versionadded:: 2017.7.0 :configuration: This module accepts explicit elb credentials but can also utilize IAM roles assigned to the instance through Instance Profiles. Dynamic credentials are then automatically obtained from AWS API and no further configuration is necessary. More Information available at: .. code-block:: text http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/iam-roles-for-amazon-ec2.html If IAM roles are not used you need to specify them either in a pillar or in the minion's config file: .. code-block:: yaml elbv2.keyid: GKTADJGHEIQSXMKKRBJ08H elbv2.key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs elbv2.region: us-west-2 If a region is not specified, the default is us-east-1. It's also possible to specify key, keyid and region via a profile, either as a passed in dict, or as a string to pull from pillars or minion config: .. code-block:: yaml myprofile: keyid: GKTADJGHEIQSXMKKRBJ08H key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs region: us-east-1 :depends: boto3 ''' # keep lint from choking on _get_conn and _cache_id # pylint: disable=E0602 from __future__ import absolute_import, print_function, unicode_literals # Import Python libs import logging log = logging.getLogger(__name__) # Import Salt libs from salt.ext import six import salt.utils.versions # Import third-party libs try: # pylint: disable=unused-import import boto3 import botocore # pylint: enable=unused-import # TODO Version check using salt.utils.versions from botocore.exceptions import ClientError logging.getLogger('boto3').setLevel(logging.CRITICAL) HAS_BOTO = True except ImportError: HAS_BOTO = False def __virtual__(): ''' Only load if boto3 libraries exist. ''' has_boto_reqs = salt.utils.versions.check_boto_reqs() if has_boto_reqs is True: __utils__['boto3.assign_funcs'](__name__, 'elbv2') return has_boto_reqs def create_target_group(name, protocol, port, vpc_id, region=None, key=None, keyid=None, profile=None, health_check_protocol='HTTP', health_check_port='traffic-port', health_check_path='/', health_check_interval_seconds=30, health_check_timeout_seconds=5, healthy_threshold_count=5, unhealthy_threshold_count=2): ''' Create target group if not present. name (string) - The name of the target group. protocol (string) - The protocol to use for routing traffic to the targets port (int) - The port on which the targets receive traffic. This port is used unless you specify a port override when registering the traffic. vpc_id (string) - The identifier of the virtual private cloud (VPC). health_check_protocol (string) - The protocol the load balancer uses when performing health check on targets. The default is the HTTP protocol. health_check_port (string) - The port the load balancer uses when performing health checks on targets. The default is 'traffic-port', which indicates the port on which each target receives traffic from the load balancer. health_check_path (string) - The ping path that is the destination on the targets for health checks. The default is /. health_check_interval_seconds (integer) - The approximate amount of time, in seconds, between health checks of an individual target. The default is 30 seconds. health_check_timeout_seconds (integer) - The amount of time, in seconds, during which no response from a target means a failed health check. The default is 5 seconds. healthy_threshold_count (integer) - The number of consecutive health checks successes required before considering an unhealthy target healthy. The default is 5. unhealthy_threshold_count (integer) - The number of consecutive health check failures required before considering a target unhealthy. The default is 2. returns (bool) - True on success, False on failure. CLI example: .. code-block:: bash salt myminion boto_elbv2.create_target_group learn1give1 protocol=HTTP port=54006 vpc_id=vpc-deadbeef ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if target_group_exists(name, region, key, keyid, profile): return True try: alb = conn.create_target_group(Name=name, Protocol=protocol, Port=port, VpcId=vpc_id, HealthCheckProtocol=health_check_protocol, HealthCheckPort=health_check_port, HealthCheckPath=health_check_path, HealthCheckIntervalSeconds=health_check_interval_seconds, HealthCheckTimeoutSeconds=health_check_timeout_seconds, HealthyThresholdCount=healthy_threshold_count, UnhealthyThresholdCount=unhealthy_threshold_count) if alb: log.info('Created ALB %s: %s', name, alb['TargetGroups'][0]['TargetGroupArn']) return True else: log.error('Failed to create ALB %s', name) return False except ClientError as error: log.error( 'Failed to create ALB %s: %s: %s', name, error.response['Error']['Code'], error.response['Error']['Message'], exc_info_on_loglevel=logging.DEBUG ) def target_group_exists(name, region=None, key=None, keyid=None, profile=None): ''' Check to see if an target group exists. CLI example: .. code-block:: bash salt myminion boto_elbv2.target_group_exists arn:aws:elasticloadbalancing:us-west-2:644138682826:targetgroup/learn1give1-api/414788a16b5cf163 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: if name.startswith('arn:aws:elasticloadbalancing'): alb = conn.describe_target_groups(TargetGroupArns=[name]) else: alb = conn.describe_target_groups(Names=[name]) if alb: return True else: log.warning('The target group does not exist in region %s', region) return False except ClientError as error: log.warning('target_group_exists check for %s returned: %s', name, error) return False def describe_target_health(name, targets=None, region=None, key=None, keyid=None, profile=None): ''' Get the curret health check status for targets in a target group. CLI example: .. code-block:: bash salt myminion boto_elbv2.describe_target_health arn:aws:elasticloadbalancing:us-west-2:644138682826:targetgroup/learn1give1-api/414788a16b5cf163 targets=["i-isdf23ifjf"] ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: if targets: targetsdict = [] for target in targets: targetsdict.append({"Id": target}) instances = conn.describe_target_health(TargetGroupArn=name, Targets=targetsdict) else: instances = conn.describe_target_health(TargetGroupArn=name) ret = {} for instance in instances['TargetHealthDescriptions']: ret.update({instance['Target']['Id']: instance['TargetHealth']['State']}) return ret except ClientError as error: log.warning(error) return {} def register_targets(name, targets, region=None, key=None, keyid=None, profile=None): ''' Register targets to a target froup of an ALB. ``targets`` is either a instance id string or a list of instance id's. Returns: - ``True``: instance(s) registered successfully - ``False``: instance(s) failed to be registered CLI example: .. code-block:: bash salt myminion boto_elbv2.register_targets myelb instance_id salt myminion boto_elbv2.register_targets myelb "[instance_id,instance_id]" ''' targetsdict = [] if isinstance(targets, six.string_types) or isinstance(targets, six.text_type): targetsdict.append({"Id": targets}) else: for target in targets: targetsdict.append({"Id": target}) conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: registered_targets = conn.register_targets(TargetGroupArn=name, Targets=targetsdict) if registered_targets: return True return False except ClientError as error: log.warning(error) return False def deregister_targets(name, targets, region=None, key=None, keyid=None, profile=None): ''' Deregister targets to a target froup of an ALB. ``targets`` is either a instance id string or a list of instance id's. Returns: - ``True``: instance(s) deregistered successfully - ``False``: instance(s) failed to be deregistered CLI example: .. code-block:: bash salt myminion boto_elbv2.deregister_targets myelb instance_id salt myminion boto_elbv2.deregister_targets myelb "[instance_id,instance_id]" ''' targetsdict = [] if isinstance(targets, six.string_types) or isinstance(targets, six.text_type): targetsdict.append({"Id": targets}) else: for target in targets: targetsdict.append({"Id": target}) conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: registered_targets = conn.deregister_targets(TargetGroupArn=name, Targets=targetsdict) if registered_targets: return True return False except ClientError as error: log.warning(error) return False def describe_load_balancers(names=None, load_balancer_arns=None, region=None, key=None, keyid=None, profile=None): ''' Describes the specified load balancer or all of your load balancers. Returns: list CLI example: .. code-block:: bash salt myminion boto_elbv2.describe_load_balancers salt myminion boto_elbv2.describe_load_balancers alb_name salt myminion boto_elbv2.describe_load_balancers "[alb_name,alb_name]" ''' if names and load_balancer_arns: raise SaltInvocationError('At most one of names or load_balancer_arns may ' 'be provided') if names: albs = names elif load_balancer_arns: albs = load_balancer_arns else: albs = None albs_list = [] if albs: if isinstance(albs, str) or isinstance(albs, six.text_type): albs_list.append(albs) else: for alb in albs: albs_list.append(alb) conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: if names: ret = conn.describe_load_balancers(Names=albs_list)['LoadBalancers'] elif load_balancer_arns: ret = conn.describe_load_balancers(LoadBalancerArns=albs_list)['LoadBalancers'] else: ret = [] next_marker = '' while True: r = conn.describe_load_balancers(Marker=next_marker) for alb in r['LoadBalancers']: ret.append(alb) if 'NextMarker' in r: next_marker = r['NextMarker'] else: break return ret if ret else [] except ClientError as error: log.warning(error) return False def describe_target_groups(names=None, target_group_arns=None, load_balancer_arn=None, region=None, key=None, keyid=None, profile=None): ''' Describes the specified target groups or all of your target groups. By default, all target groups are described. Alternatively, you can specify one of the following to filter the results: the ARN of the load balancer, the names of one or more target groups, or the ARNs of one or more target groups. Returns: list CLI example: .. code-block:: bash salt myminion boto_elbv2.describe_target_groups salt myminion boto_elbv2.describe_target_groups target_group_name salt myminion boto_elbv2.describe_target_groups "[tg_name,tg_name]" ''' if names and target_group_arns: raise SaltInvocationError('At most one of names or target_group_arns may ' 'be provided') if names: target_groups = names elif target_group_arns: target_groups = target_group_arns else: target_groups = None tg_list = [] if target_groups: if isinstance(target_groups, str) or isinstance(target_groups, six.text_type): tg_list.append(target_groups) else: for group in target_groups: tg_list.append(group) conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: if names: ret = conn.describe_target_groups(Names=tg_list)['TargetGroups'] elif target_group_arns: ret = conn.describe_target_groups(TargetGroupArns=tg_list)['TargetGroups'] elif load_balancer_arn: ret = conn.describe_target_groups(LoadBalancerArn=load_balancer_arn)['TargetGroups'] else: ret = [] next_marker = '' while True: r = conn.describe_target_groups(Marker=next_marker) for alb in r['TargetGroups']: ret.append(alb) if 'NextMarker' in r: next_marker = r['NextMarker'] else: break return ret if ret else [] except ClientError as error: log.warning(error) return False
saltstack/salt
salt/modules/boto_elbv2.py
target_group_exists
python
def target_group_exists(name, region=None, key=None, keyid=None, profile=None): ''' Check to see if an target group exists. CLI example: .. code-block:: bash salt myminion boto_elbv2.target_group_exists arn:aws:elasticloadbalancing:us-west-2:644138682826:targetgroup/learn1give1-api/414788a16b5cf163 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: if name.startswith('arn:aws:elasticloadbalancing'): alb = conn.describe_target_groups(TargetGroupArns=[name]) else: alb = conn.describe_target_groups(Names=[name]) if alb: return True else: log.warning('The target group does not exist in region %s', region) return False except ClientError as error: log.warning('target_group_exists check for %s returned: %s', name, error) return False
Check to see if an target group exists. CLI example: .. code-block:: bash salt myminion boto_elbv2.target_group_exists arn:aws:elasticloadbalancing:us-west-2:644138682826:targetgroup/learn1give1-api/414788a16b5cf163
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_elbv2.py#L209-L237
null
# -*- coding: utf-8 -*- ''' Connection module for Amazon ALB .. versionadded:: 2017.7.0 :configuration: This module accepts explicit elb credentials but can also utilize IAM roles assigned to the instance through Instance Profiles. Dynamic credentials are then automatically obtained from AWS API and no further configuration is necessary. More Information available at: .. code-block:: text http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/iam-roles-for-amazon-ec2.html If IAM roles are not used you need to specify them either in a pillar or in the minion's config file: .. code-block:: yaml elbv2.keyid: GKTADJGHEIQSXMKKRBJ08H elbv2.key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs elbv2.region: us-west-2 If a region is not specified, the default is us-east-1. It's also possible to specify key, keyid and region via a profile, either as a passed in dict, or as a string to pull from pillars or minion config: .. code-block:: yaml myprofile: keyid: GKTADJGHEIQSXMKKRBJ08H key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs region: us-east-1 :depends: boto3 ''' # keep lint from choking on _get_conn and _cache_id # pylint: disable=E0602 from __future__ import absolute_import, print_function, unicode_literals # Import Python libs import logging log = logging.getLogger(__name__) # Import Salt libs from salt.ext import six import salt.utils.versions # Import third-party libs try: # pylint: disable=unused-import import boto3 import botocore # pylint: enable=unused-import # TODO Version check using salt.utils.versions from botocore.exceptions import ClientError logging.getLogger('boto3').setLevel(logging.CRITICAL) HAS_BOTO = True except ImportError: HAS_BOTO = False def __virtual__(): ''' Only load if boto3 libraries exist. ''' has_boto_reqs = salt.utils.versions.check_boto_reqs() if has_boto_reqs is True: __utils__['boto3.assign_funcs'](__name__, 'elbv2') return has_boto_reqs def create_target_group(name, protocol, port, vpc_id, region=None, key=None, keyid=None, profile=None, health_check_protocol='HTTP', health_check_port='traffic-port', health_check_path='/', health_check_interval_seconds=30, health_check_timeout_seconds=5, healthy_threshold_count=5, unhealthy_threshold_count=2): ''' Create target group if not present. name (string) - The name of the target group. protocol (string) - The protocol to use for routing traffic to the targets port (int) - The port on which the targets receive traffic. This port is used unless you specify a port override when registering the traffic. vpc_id (string) - The identifier of the virtual private cloud (VPC). health_check_protocol (string) - The protocol the load balancer uses when performing health check on targets. The default is the HTTP protocol. health_check_port (string) - The port the load balancer uses when performing health checks on targets. The default is 'traffic-port', which indicates the port on which each target receives traffic from the load balancer. health_check_path (string) - The ping path that is the destination on the targets for health checks. The default is /. health_check_interval_seconds (integer) - The approximate amount of time, in seconds, between health checks of an individual target. The default is 30 seconds. health_check_timeout_seconds (integer) - The amount of time, in seconds, during which no response from a target means a failed health check. The default is 5 seconds. healthy_threshold_count (integer) - The number of consecutive health checks successes required before considering an unhealthy target healthy. The default is 5. unhealthy_threshold_count (integer) - The number of consecutive health check failures required before considering a target unhealthy. The default is 2. returns (bool) - True on success, False on failure. CLI example: .. code-block:: bash salt myminion boto_elbv2.create_target_group learn1give1 protocol=HTTP port=54006 vpc_id=vpc-deadbeef ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if target_group_exists(name, region, key, keyid, profile): return True try: alb = conn.create_target_group(Name=name, Protocol=protocol, Port=port, VpcId=vpc_id, HealthCheckProtocol=health_check_protocol, HealthCheckPort=health_check_port, HealthCheckPath=health_check_path, HealthCheckIntervalSeconds=health_check_interval_seconds, HealthCheckTimeoutSeconds=health_check_timeout_seconds, HealthyThresholdCount=healthy_threshold_count, UnhealthyThresholdCount=unhealthy_threshold_count) if alb: log.info('Created ALB %s: %s', name, alb['TargetGroups'][0]['TargetGroupArn']) return True else: log.error('Failed to create ALB %s', name) return False except ClientError as error: log.error( 'Failed to create ALB %s: %s: %s', name, error.response['Error']['Code'], error.response['Error']['Message'], exc_info_on_loglevel=logging.DEBUG ) def delete_target_group(name, region=None, key=None, keyid=None, profile=None): ''' Delete target group. name (string) - Target Group Name or Amazon Resource Name (ARN). returns (bool) - True on success, False on failure. CLI example: .. code-block:: bash salt myminion boto_elbv2.delete_target_group arn:aws:elasticloadbalancing:us-west-2:644138682826:targetgroup/learn1give1-api/414788a16b5cf163 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not target_group_exists(name, region, key, keyid, profile): return True try: if name.startswith('arn:aws:elasticloadbalancing'): conn.delete_target_group(TargetGroupArn=name) log.info('Deleted target group %s', name) else: tg_info = conn.describe_target_groups(Names=[name]) if len(tg_info['TargetGroups']) != 1: return False arn = tg_info['TargetGroups'][0]['TargetGroupArn'] conn.delete_target_group(TargetGroupArn=arn) log.info('Deleted target group %s ARN %s', name, arn) return True except ClientError as error: log.error('Failed to delete target group %s', name, exc_info_on_loglevel=logging.DEBUG) return False def describe_target_health(name, targets=None, region=None, key=None, keyid=None, profile=None): ''' Get the curret health check status for targets in a target group. CLI example: .. code-block:: bash salt myminion boto_elbv2.describe_target_health arn:aws:elasticloadbalancing:us-west-2:644138682826:targetgroup/learn1give1-api/414788a16b5cf163 targets=["i-isdf23ifjf"] ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: if targets: targetsdict = [] for target in targets: targetsdict.append({"Id": target}) instances = conn.describe_target_health(TargetGroupArn=name, Targets=targetsdict) else: instances = conn.describe_target_health(TargetGroupArn=name) ret = {} for instance in instances['TargetHealthDescriptions']: ret.update({instance['Target']['Id']: instance['TargetHealth']['State']}) return ret except ClientError as error: log.warning(error) return {} def register_targets(name, targets, region=None, key=None, keyid=None, profile=None): ''' Register targets to a target froup of an ALB. ``targets`` is either a instance id string or a list of instance id's. Returns: - ``True``: instance(s) registered successfully - ``False``: instance(s) failed to be registered CLI example: .. code-block:: bash salt myminion boto_elbv2.register_targets myelb instance_id salt myminion boto_elbv2.register_targets myelb "[instance_id,instance_id]" ''' targetsdict = [] if isinstance(targets, six.string_types) or isinstance(targets, six.text_type): targetsdict.append({"Id": targets}) else: for target in targets: targetsdict.append({"Id": target}) conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: registered_targets = conn.register_targets(TargetGroupArn=name, Targets=targetsdict) if registered_targets: return True return False except ClientError as error: log.warning(error) return False def deregister_targets(name, targets, region=None, key=None, keyid=None, profile=None): ''' Deregister targets to a target froup of an ALB. ``targets`` is either a instance id string or a list of instance id's. Returns: - ``True``: instance(s) deregistered successfully - ``False``: instance(s) failed to be deregistered CLI example: .. code-block:: bash salt myminion boto_elbv2.deregister_targets myelb instance_id salt myminion boto_elbv2.deregister_targets myelb "[instance_id,instance_id]" ''' targetsdict = [] if isinstance(targets, six.string_types) or isinstance(targets, six.text_type): targetsdict.append({"Id": targets}) else: for target in targets: targetsdict.append({"Id": target}) conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: registered_targets = conn.deregister_targets(TargetGroupArn=name, Targets=targetsdict) if registered_targets: return True return False except ClientError as error: log.warning(error) return False def describe_load_balancers(names=None, load_balancer_arns=None, region=None, key=None, keyid=None, profile=None): ''' Describes the specified load balancer or all of your load balancers. Returns: list CLI example: .. code-block:: bash salt myminion boto_elbv2.describe_load_balancers salt myminion boto_elbv2.describe_load_balancers alb_name salt myminion boto_elbv2.describe_load_balancers "[alb_name,alb_name]" ''' if names and load_balancer_arns: raise SaltInvocationError('At most one of names or load_balancer_arns may ' 'be provided') if names: albs = names elif load_balancer_arns: albs = load_balancer_arns else: albs = None albs_list = [] if albs: if isinstance(albs, str) or isinstance(albs, six.text_type): albs_list.append(albs) else: for alb in albs: albs_list.append(alb) conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: if names: ret = conn.describe_load_balancers(Names=albs_list)['LoadBalancers'] elif load_balancer_arns: ret = conn.describe_load_balancers(LoadBalancerArns=albs_list)['LoadBalancers'] else: ret = [] next_marker = '' while True: r = conn.describe_load_balancers(Marker=next_marker) for alb in r['LoadBalancers']: ret.append(alb) if 'NextMarker' in r: next_marker = r['NextMarker'] else: break return ret if ret else [] except ClientError as error: log.warning(error) return False def describe_target_groups(names=None, target_group_arns=None, load_balancer_arn=None, region=None, key=None, keyid=None, profile=None): ''' Describes the specified target groups or all of your target groups. By default, all target groups are described. Alternatively, you can specify one of the following to filter the results: the ARN of the load balancer, the names of one or more target groups, or the ARNs of one or more target groups. Returns: list CLI example: .. code-block:: bash salt myminion boto_elbv2.describe_target_groups salt myminion boto_elbv2.describe_target_groups target_group_name salt myminion boto_elbv2.describe_target_groups "[tg_name,tg_name]" ''' if names and target_group_arns: raise SaltInvocationError('At most one of names or target_group_arns may ' 'be provided') if names: target_groups = names elif target_group_arns: target_groups = target_group_arns else: target_groups = None tg_list = [] if target_groups: if isinstance(target_groups, str) or isinstance(target_groups, six.text_type): tg_list.append(target_groups) else: for group in target_groups: tg_list.append(group) conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: if names: ret = conn.describe_target_groups(Names=tg_list)['TargetGroups'] elif target_group_arns: ret = conn.describe_target_groups(TargetGroupArns=tg_list)['TargetGroups'] elif load_balancer_arn: ret = conn.describe_target_groups(LoadBalancerArn=load_balancer_arn)['TargetGroups'] else: ret = [] next_marker = '' while True: r = conn.describe_target_groups(Marker=next_marker) for alb in r['TargetGroups']: ret.append(alb) if 'NextMarker' in r: next_marker = r['NextMarker'] else: break return ret if ret else [] except ClientError as error: log.warning(error) return False
saltstack/salt
salt/modules/boto_elbv2.py
describe_target_health
python
def describe_target_health(name, targets=None, region=None, key=None, keyid=None, profile=None): ''' Get the curret health check status for targets in a target group. CLI example: .. code-block:: bash salt myminion boto_elbv2.describe_target_health arn:aws:elasticloadbalancing:us-west-2:644138682826:targetgroup/learn1give1-api/414788a16b5cf163 targets=["i-isdf23ifjf"] ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: if targets: targetsdict = [] for target in targets: targetsdict.append({"Id": target}) instances = conn.describe_target_health(TargetGroupArn=name, Targets=targetsdict) else: instances = conn.describe_target_health(TargetGroupArn=name) ret = {} for instance in instances['TargetHealthDescriptions']: ret.update({instance['Target']['Id']: instance['TargetHealth']['State']}) return ret except ClientError as error: log.warning(error) return {}
Get the curret health check status for targets in a target group. CLI example: .. code-block:: bash salt myminion boto_elbv2.describe_target_health arn:aws:elasticloadbalancing:us-west-2:644138682826:targetgroup/learn1give1-api/414788a16b5cf163 targets=["i-isdf23ifjf"]
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_elbv2.py#L240-L272
null
# -*- coding: utf-8 -*- ''' Connection module for Amazon ALB .. versionadded:: 2017.7.0 :configuration: This module accepts explicit elb credentials but can also utilize IAM roles assigned to the instance through Instance Profiles. Dynamic credentials are then automatically obtained from AWS API and no further configuration is necessary. More Information available at: .. code-block:: text http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/iam-roles-for-amazon-ec2.html If IAM roles are not used you need to specify them either in a pillar or in the minion's config file: .. code-block:: yaml elbv2.keyid: GKTADJGHEIQSXMKKRBJ08H elbv2.key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs elbv2.region: us-west-2 If a region is not specified, the default is us-east-1. It's also possible to specify key, keyid and region via a profile, either as a passed in dict, or as a string to pull from pillars or minion config: .. code-block:: yaml myprofile: keyid: GKTADJGHEIQSXMKKRBJ08H key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs region: us-east-1 :depends: boto3 ''' # keep lint from choking on _get_conn and _cache_id # pylint: disable=E0602 from __future__ import absolute_import, print_function, unicode_literals # Import Python libs import logging log = logging.getLogger(__name__) # Import Salt libs from salt.ext import six import salt.utils.versions # Import third-party libs try: # pylint: disable=unused-import import boto3 import botocore # pylint: enable=unused-import # TODO Version check using salt.utils.versions from botocore.exceptions import ClientError logging.getLogger('boto3').setLevel(logging.CRITICAL) HAS_BOTO = True except ImportError: HAS_BOTO = False def __virtual__(): ''' Only load if boto3 libraries exist. ''' has_boto_reqs = salt.utils.versions.check_boto_reqs() if has_boto_reqs is True: __utils__['boto3.assign_funcs'](__name__, 'elbv2') return has_boto_reqs def create_target_group(name, protocol, port, vpc_id, region=None, key=None, keyid=None, profile=None, health_check_protocol='HTTP', health_check_port='traffic-port', health_check_path='/', health_check_interval_seconds=30, health_check_timeout_seconds=5, healthy_threshold_count=5, unhealthy_threshold_count=2): ''' Create target group if not present. name (string) - The name of the target group. protocol (string) - The protocol to use for routing traffic to the targets port (int) - The port on which the targets receive traffic. This port is used unless you specify a port override when registering the traffic. vpc_id (string) - The identifier of the virtual private cloud (VPC). health_check_protocol (string) - The protocol the load balancer uses when performing health check on targets. The default is the HTTP protocol. health_check_port (string) - The port the load balancer uses when performing health checks on targets. The default is 'traffic-port', which indicates the port on which each target receives traffic from the load balancer. health_check_path (string) - The ping path that is the destination on the targets for health checks. The default is /. health_check_interval_seconds (integer) - The approximate amount of time, in seconds, between health checks of an individual target. The default is 30 seconds. health_check_timeout_seconds (integer) - The amount of time, in seconds, during which no response from a target means a failed health check. The default is 5 seconds. healthy_threshold_count (integer) - The number of consecutive health checks successes required before considering an unhealthy target healthy. The default is 5. unhealthy_threshold_count (integer) - The number of consecutive health check failures required before considering a target unhealthy. The default is 2. returns (bool) - True on success, False on failure. CLI example: .. code-block:: bash salt myminion boto_elbv2.create_target_group learn1give1 protocol=HTTP port=54006 vpc_id=vpc-deadbeef ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if target_group_exists(name, region, key, keyid, profile): return True try: alb = conn.create_target_group(Name=name, Protocol=protocol, Port=port, VpcId=vpc_id, HealthCheckProtocol=health_check_protocol, HealthCheckPort=health_check_port, HealthCheckPath=health_check_path, HealthCheckIntervalSeconds=health_check_interval_seconds, HealthCheckTimeoutSeconds=health_check_timeout_seconds, HealthyThresholdCount=healthy_threshold_count, UnhealthyThresholdCount=unhealthy_threshold_count) if alb: log.info('Created ALB %s: %s', name, alb['TargetGroups'][0]['TargetGroupArn']) return True else: log.error('Failed to create ALB %s', name) return False except ClientError as error: log.error( 'Failed to create ALB %s: %s: %s', name, error.response['Error']['Code'], error.response['Error']['Message'], exc_info_on_loglevel=logging.DEBUG ) def delete_target_group(name, region=None, key=None, keyid=None, profile=None): ''' Delete target group. name (string) - Target Group Name or Amazon Resource Name (ARN). returns (bool) - True on success, False on failure. CLI example: .. code-block:: bash salt myminion boto_elbv2.delete_target_group arn:aws:elasticloadbalancing:us-west-2:644138682826:targetgroup/learn1give1-api/414788a16b5cf163 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not target_group_exists(name, region, key, keyid, profile): return True try: if name.startswith('arn:aws:elasticloadbalancing'): conn.delete_target_group(TargetGroupArn=name) log.info('Deleted target group %s', name) else: tg_info = conn.describe_target_groups(Names=[name]) if len(tg_info['TargetGroups']) != 1: return False arn = tg_info['TargetGroups'][0]['TargetGroupArn'] conn.delete_target_group(TargetGroupArn=arn) log.info('Deleted target group %s ARN %s', name, arn) return True except ClientError as error: log.error('Failed to delete target group %s', name, exc_info_on_loglevel=logging.DEBUG) return False def target_group_exists(name, region=None, key=None, keyid=None, profile=None): ''' Check to see if an target group exists. CLI example: .. code-block:: bash salt myminion boto_elbv2.target_group_exists arn:aws:elasticloadbalancing:us-west-2:644138682826:targetgroup/learn1give1-api/414788a16b5cf163 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: if name.startswith('arn:aws:elasticloadbalancing'): alb = conn.describe_target_groups(TargetGroupArns=[name]) else: alb = conn.describe_target_groups(Names=[name]) if alb: return True else: log.warning('The target group does not exist in region %s', region) return False except ClientError as error: log.warning('target_group_exists check for %s returned: %s', name, error) return False def register_targets(name, targets, region=None, key=None, keyid=None, profile=None): ''' Register targets to a target froup of an ALB. ``targets`` is either a instance id string or a list of instance id's. Returns: - ``True``: instance(s) registered successfully - ``False``: instance(s) failed to be registered CLI example: .. code-block:: bash salt myminion boto_elbv2.register_targets myelb instance_id salt myminion boto_elbv2.register_targets myelb "[instance_id,instance_id]" ''' targetsdict = [] if isinstance(targets, six.string_types) or isinstance(targets, six.text_type): targetsdict.append({"Id": targets}) else: for target in targets: targetsdict.append({"Id": target}) conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: registered_targets = conn.register_targets(TargetGroupArn=name, Targets=targetsdict) if registered_targets: return True return False except ClientError as error: log.warning(error) return False def deregister_targets(name, targets, region=None, key=None, keyid=None, profile=None): ''' Deregister targets to a target froup of an ALB. ``targets`` is either a instance id string or a list of instance id's. Returns: - ``True``: instance(s) deregistered successfully - ``False``: instance(s) failed to be deregistered CLI example: .. code-block:: bash salt myminion boto_elbv2.deregister_targets myelb instance_id salt myminion boto_elbv2.deregister_targets myelb "[instance_id,instance_id]" ''' targetsdict = [] if isinstance(targets, six.string_types) or isinstance(targets, six.text_type): targetsdict.append({"Id": targets}) else: for target in targets: targetsdict.append({"Id": target}) conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: registered_targets = conn.deregister_targets(TargetGroupArn=name, Targets=targetsdict) if registered_targets: return True return False except ClientError as error: log.warning(error) return False def describe_load_balancers(names=None, load_balancer_arns=None, region=None, key=None, keyid=None, profile=None): ''' Describes the specified load balancer or all of your load balancers. Returns: list CLI example: .. code-block:: bash salt myminion boto_elbv2.describe_load_balancers salt myminion boto_elbv2.describe_load_balancers alb_name salt myminion boto_elbv2.describe_load_balancers "[alb_name,alb_name]" ''' if names and load_balancer_arns: raise SaltInvocationError('At most one of names or load_balancer_arns may ' 'be provided') if names: albs = names elif load_balancer_arns: albs = load_balancer_arns else: albs = None albs_list = [] if albs: if isinstance(albs, str) or isinstance(albs, six.text_type): albs_list.append(albs) else: for alb in albs: albs_list.append(alb) conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: if names: ret = conn.describe_load_balancers(Names=albs_list)['LoadBalancers'] elif load_balancer_arns: ret = conn.describe_load_balancers(LoadBalancerArns=albs_list)['LoadBalancers'] else: ret = [] next_marker = '' while True: r = conn.describe_load_balancers(Marker=next_marker) for alb in r['LoadBalancers']: ret.append(alb) if 'NextMarker' in r: next_marker = r['NextMarker'] else: break return ret if ret else [] except ClientError as error: log.warning(error) return False def describe_target_groups(names=None, target_group_arns=None, load_balancer_arn=None, region=None, key=None, keyid=None, profile=None): ''' Describes the specified target groups or all of your target groups. By default, all target groups are described. Alternatively, you can specify one of the following to filter the results: the ARN of the load balancer, the names of one or more target groups, or the ARNs of one or more target groups. Returns: list CLI example: .. code-block:: bash salt myminion boto_elbv2.describe_target_groups salt myminion boto_elbv2.describe_target_groups target_group_name salt myminion boto_elbv2.describe_target_groups "[tg_name,tg_name]" ''' if names and target_group_arns: raise SaltInvocationError('At most one of names or target_group_arns may ' 'be provided') if names: target_groups = names elif target_group_arns: target_groups = target_group_arns else: target_groups = None tg_list = [] if target_groups: if isinstance(target_groups, str) or isinstance(target_groups, six.text_type): tg_list.append(target_groups) else: for group in target_groups: tg_list.append(group) conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: if names: ret = conn.describe_target_groups(Names=tg_list)['TargetGroups'] elif target_group_arns: ret = conn.describe_target_groups(TargetGroupArns=tg_list)['TargetGroups'] elif load_balancer_arn: ret = conn.describe_target_groups(LoadBalancerArn=load_balancer_arn)['TargetGroups'] else: ret = [] next_marker = '' while True: r = conn.describe_target_groups(Marker=next_marker) for alb in r['TargetGroups']: ret.append(alb) if 'NextMarker' in r: next_marker = r['NextMarker'] else: break return ret if ret else [] except ClientError as error: log.warning(error) return False
saltstack/salt
salt/modules/boto_elbv2.py
register_targets
python
def register_targets(name, targets, region=None, key=None, keyid=None, profile=None): ''' Register targets to a target froup of an ALB. ``targets`` is either a instance id string or a list of instance id's. Returns: - ``True``: instance(s) registered successfully - ``False``: instance(s) failed to be registered CLI example: .. code-block:: bash salt myminion boto_elbv2.register_targets myelb instance_id salt myminion boto_elbv2.register_targets myelb "[instance_id,instance_id]" ''' targetsdict = [] if isinstance(targets, six.string_types) or isinstance(targets, six.text_type): targetsdict.append({"Id": targets}) else: for target in targets: targetsdict.append({"Id": target}) conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: registered_targets = conn.register_targets(TargetGroupArn=name, Targets=targetsdict) if registered_targets: return True return False except ClientError as error: log.warning(error) return False
Register targets to a target froup of an ALB. ``targets`` is either a instance id string or a list of instance id's. Returns: - ``True``: instance(s) registered successfully - ``False``: instance(s) failed to be registered CLI example: .. code-block:: bash salt myminion boto_elbv2.register_targets myelb instance_id salt myminion boto_elbv2.register_targets myelb "[instance_id,instance_id]"
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_elbv2.py#L275-L312
null
# -*- coding: utf-8 -*- ''' Connection module for Amazon ALB .. versionadded:: 2017.7.0 :configuration: This module accepts explicit elb credentials but can also utilize IAM roles assigned to the instance through Instance Profiles. Dynamic credentials are then automatically obtained from AWS API and no further configuration is necessary. More Information available at: .. code-block:: text http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/iam-roles-for-amazon-ec2.html If IAM roles are not used you need to specify them either in a pillar or in the minion's config file: .. code-block:: yaml elbv2.keyid: GKTADJGHEIQSXMKKRBJ08H elbv2.key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs elbv2.region: us-west-2 If a region is not specified, the default is us-east-1. It's also possible to specify key, keyid and region via a profile, either as a passed in dict, or as a string to pull from pillars or minion config: .. code-block:: yaml myprofile: keyid: GKTADJGHEIQSXMKKRBJ08H key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs region: us-east-1 :depends: boto3 ''' # keep lint from choking on _get_conn and _cache_id # pylint: disable=E0602 from __future__ import absolute_import, print_function, unicode_literals # Import Python libs import logging log = logging.getLogger(__name__) # Import Salt libs from salt.ext import six import salt.utils.versions # Import third-party libs try: # pylint: disable=unused-import import boto3 import botocore # pylint: enable=unused-import # TODO Version check using salt.utils.versions from botocore.exceptions import ClientError logging.getLogger('boto3').setLevel(logging.CRITICAL) HAS_BOTO = True except ImportError: HAS_BOTO = False def __virtual__(): ''' Only load if boto3 libraries exist. ''' has_boto_reqs = salt.utils.versions.check_boto_reqs() if has_boto_reqs is True: __utils__['boto3.assign_funcs'](__name__, 'elbv2') return has_boto_reqs def create_target_group(name, protocol, port, vpc_id, region=None, key=None, keyid=None, profile=None, health_check_protocol='HTTP', health_check_port='traffic-port', health_check_path='/', health_check_interval_seconds=30, health_check_timeout_seconds=5, healthy_threshold_count=5, unhealthy_threshold_count=2): ''' Create target group if not present. name (string) - The name of the target group. protocol (string) - The protocol to use for routing traffic to the targets port (int) - The port on which the targets receive traffic. This port is used unless you specify a port override when registering the traffic. vpc_id (string) - The identifier of the virtual private cloud (VPC). health_check_protocol (string) - The protocol the load balancer uses when performing health check on targets. The default is the HTTP protocol. health_check_port (string) - The port the load balancer uses when performing health checks on targets. The default is 'traffic-port', which indicates the port on which each target receives traffic from the load balancer. health_check_path (string) - The ping path that is the destination on the targets for health checks. The default is /. health_check_interval_seconds (integer) - The approximate amount of time, in seconds, between health checks of an individual target. The default is 30 seconds. health_check_timeout_seconds (integer) - The amount of time, in seconds, during which no response from a target means a failed health check. The default is 5 seconds. healthy_threshold_count (integer) - The number of consecutive health checks successes required before considering an unhealthy target healthy. The default is 5. unhealthy_threshold_count (integer) - The number of consecutive health check failures required before considering a target unhealthy. The default is 2. returns (bool) - True on success, False on failure. CLI example: .. code-block:: bash salt myminion boto_elbv2.create_target_group learn1give1 protocol=HTTP port=54006 vpc_id=vpc-deadbeef ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if target_group_exists(name, region, key, keyid, profile): return True try: alb = conn.create_target_group(Name=name, Protocol=protocol, Port=port, VpcId=vpc_id, HealthCheckProtocol=health_check_protocol, HealthCheckPort=health_check_port, HealthCheckPath=health_check_path, HealthCheckIntervalSeconds=health_check_interval_seconds, HealthCheckTimeoutSeconds=health_check_timeout_seconds, HealthyThresholdCount=healthy_threshold_count, UnhealthyThresholdCount=unhealthy_threshold_count) if alb: log.info('Created ALB %s: %s', name, alb['TargetGroups'][0]['TargetGroupArn']) return True else: log.error('Failed to create ALB %s', name) return False except ClientError as error: log.error( 'Failed to create ALB %s: %s: %s', name, error.response['Error']['Code'], error.response['Error']['Message'], exc_info_on_loglevel=logging.DEBUG ) def delete_target_group(name, region=None, key=None, keyid=None, profile=None): ''' Delete target group. name (string) - Target Group Name or Amazon Resource Name (ARN). returns (bool) - True on success, False on failure. CLI example: .. code-block:: bash salt myminion boto_elbv2.delete_target_group arn:aws:elasticloadbalancing:us-west-2:644138682826:targetgroup/learn1give1-api/414788a16b5cf163 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not target_group_exists(name, region, key, keyid, profile): return True try: if name.startswith('arn:aws:elasticloadbalancing'): conn.delete_target_group(TargetGroupArn=name) log.info('Deleted target group %s', name) else: tg_info = conn.describe_target_groups(Names=[name]) if len(tg_info['TargetGroups']) != 1: return False arn = tg_info['TargetGroups'][0]['TargetGroupArn'] conn.delete_target_group(TargetGroupArn=arn) log.info('Deleted target group %s ARN %s', name, arn) return True except ClientError as error: log.error('Failed to delete target group %s', name, exc_info_on_loglevel=logging.DEBUG) return False def target_group_exists(name, region=None, key=None, keyid=None, profile=None): ''' Check to see if an target group exists. CLI example: .. code-block:: bash salt myminion boto_elbv2.target_group_exists arn:aws:elasticloadbalancing:us-west-2:644138682826:targetgroup/learn1give1-api/414788a16b5cf163 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: if name.startswith('arn:aws:elasticloadbalancing'): alb = conn.describe_target_groups(TargetGroupArns=[name]) else: alb = conn.describe_target_groups(Names=[name]) if alb: return True else: log.warning('The target group does not exist in region %s', region) return False except ClientError as error: log.warning('target_group_exists check for %s returned: %s', name, error) return False def describe_target_health(name, targets=None, region=None, key=None, keyid=None, profile=None): ''' Get the curret health check status for targets in a target group. CLI example: .. code-block:: bash salt myminion boto_elbv2.describe_target_health arn:aws:elasticloadbalancing:us-west-2:644138682826:targetgroup/learn1give1-api/414788a16b5cf163 targets=["i-isdf23ifjf"] ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: if targets: targetsdict = [] for target in targets: targetsdict.append({"Id": target}) instances = conn.describe_target_health(TargetGroupArn=name, Targets=targetsdict) else: instances = conn.describe_target_health(TargetGroupArn=name) ret = {} for instance in instances['TargetHealthDescriptions']: ret.update({instance['Target']['Id']: instance['TargetHealth']['State']}) return ret except ClientError as error: log.warning(error) return {} def deregister_targets(name, targets, region=None, key=None, keyid=None, profile=None): ''' Deregister targets to a target froup of an ALB. ``targets`` is either a instance id string or a list of instance id's. Returns: - ``True``: instance(s) deregistered successfully - ``False``: instance(s) failed to be deregistered CLI example: .. code-block:: bash salt myminion boto_elbv2.deregister_targets myelb instance_id salt myminion boto_elbv2.deregister_targets myelb "[instance_id,instance_id]" ''' targetsdict = [] if isinstance(targets, six.string_types) or isinstance(targets, six.text_type): targetsdict.append({"Id": targets}) else: for target in targets: targetsdict.append({"Id": target}) conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: registered_targets = conn.deregister_targets(TargetGroupArn=name, Targets=targetsdict) if registered_targets: return True return False except ClientError as error: log.warning(error) return False def describe_load_balancers(names=None, load_balancer_arns=None, region=None, key=None, keyid=None, profile=None): ''' Describes the specified load balancer or all of your load balancers. Returns: list CLI example: .. code-block:: bash salt myminion boto_elbv2.describe_load_balancers salt myminion boto_elbv2.describe_load_balancers alb_name salt myminion boto_elbv2.describe_load_balancers "[alb_name,alb_name]" ''' if names and load_balancer_arns: raise SaltInvocationError('At most one of names or load_balancer_arns may ' 'be provided') if names: albs = names elif load_balancer_arns: albs = load_balancer_arns else: albs = None albs_list = [] if albs: if isinstance(albs, str) or isinstance(albs, six.text_type): albs_list.append(albs) else: for alb in albs: albs_list.append(alb) conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: if names: ret = conn.describe_load_balancers(Names=albs_list)['LoadBalancers'] elif load_balancer_arns: ret = conn.describe_load_balancers(LoadBalancerArns=albs_list)['LoadBalancers'] else: ret = [] next_marker = '' while True: r = conn.describe_load_balancers(Marker=next_marker) for alb in r['LoadBalancers']: ret.append(alb) if 'NextMarker' in r: next_marker = r['NextMarker'] else: break return ret if ret else [] except ClientError as error: log.warning(error) return False def describe_target_groups(names=None, target_group_arns=None, load_balancer_arn=None, region=None, key=None, keyid=None, profile=None): ''' Describes the specified target groups or all of your target groups. By default, all target groups are described. Alternatively, you can specify one of the following to filter the results: the ARN of the load balancer, the names of one or more target groups, or the ARNs of one or more target groups. Returns: list CLI example: .. code-block:: bash salt myminion boto_elbv2.describe_target_groups salt myminion boto_elbv2.describe_target_groups target_group_name salt myminion boto_elbv2.describe_target_groups "[tg_name,tg_name]" ''' if names and target_group_arns: raise SaltInvocationError('At most one of names or target_group_arns may ' 'be provided') if names: target_groups = names elif target_group_arns: target_groups = target_group_arns else: target_groups = None tg_list = [] if target_groups: if isinstance(target_groups, str) or isinstance(target_groups, six.text_type): tg_list.append(target_groups) else: for group in target_groups: tg_list.append(group) conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: if names: ret = conn.describe_target_groups(Names=tg_list)['TargetGroups'] elif target_group_arns: ret = conn.describe_target_groups(TargetGroupArns=tg_list)['TargetGroups'] elif load_balancer_arn: ret = conn.describe_target_groups(LoadBalancerArn=load_balancer_arn)['TargetGroups'] else: ret = [] next_marker = '' while True: r = conn.describe_target_groups(Marker=next_marker) for alb in r['TargetGroups']: ret.append(alb) if 'NextMarker' in r: next_marker = r['NextMarker'] else: break return ret if ret else [] except ClientError as error: log.warning(error) return False
saltstack/salt
salt/modules/boto_elbv2.py
describe_load_balancers
python
def describe_load_balancers(names=None, load_balancer_arns=None, region=None, key=None, keyid=None, profile=None): ''' Describes the specified load balancer or all of your load balancers. Returns: list CLI example: .. code-block:: bash salt myminion boto_elbv2.describe_load_balancers salt myminion boto_elbv2.describe_load_balancers alb_name salt myminion boto_elbv2.describe_load_balancers "[alb_name,alb_name]" ''' if names and load_balancer_arns: raise SaltInvocationError('At most one of names or load_balancer_arns may ' 'be provided') if names: albs = names elif load_balancer_arns: albs = load_balancer_arns else: albs = None albs_list = [] if albs: if isinstance(albs, str) or isinstance(albs, six.text_type): albs_list.append(albs) else: for alb in albs: albs_list.append(alb) conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: if names: ret = conn.describe_load_balancers(Names=albs_list)['LoadBalancers'] elif load_balancer_arns: ret = conn.describe_load_balancers(LoadBalancerArns=albs_list)['LoadBalancers'] else: ret = [] next_marker = '' while True: r = conn.describe_load_balancers(Marker=next_marker) for alb in r['LoadBalancers']: ret.append(alb) if 'NextMarker' in r: next_marker = r['NextMarker'] else: break return ret if ret else [] except ClientError as error: log.warning(error) return False
Describes the specified load balancer or all of your load balancers. Returns: list CLI example: .. code-block:: bash salt myminion boto_elbv2.describe_load_balancers salt myminion boto_elbv2.describe_load_balancers alb_name salt myminion boto_elbv2.describe_load_balancers "[alb_name,alb_name]"
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_elbv2.py#L355-L414
null
# -*- coding: utf-8 -*- ''' Connection module for Amazon ALB .. versionadded:: 2017.7.0 :configuration: This module accepts explicit elb credentials but can also utilize IAM roles assigned to the instance through Instance Profiles. Dynamic credentials are then automatically obtained from AWS API and no further configuration is necessary. More Information available at: .. code-block:: text http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/iam-roles-for-amazon-ec2.html If IAM roles are not used you need to specify them either in a pillar or in the minion's config file: .. code-block:: yaml elbv2.keyid: GKTADJGHEIQSXMKKRBJ08H elbv2.key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs elbv2.region: us-west-2 If a region is not specified, the default is us-east-1. It's also possible to specify key, keyid and region via a profile, either as a passed in dict, or as a string to pull from pillars or minion config: .. code-block:: yaml myprofile: keyid: GKTADJGHEIQSXMKKRBJ08H key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs region: us-east-1 :depends: boto3 ''' # keep lint from choking on _get_conn and _cache_id # pylint: disable=E0602 from __future__ import absolute_import, print_function, unicode_literals # Import Python libs import logging log = logging.getLogger(__name__) # Import Salt libs from salt.ext import six import salt.utils.versions # Import third-party libs try: # pylint: disable=unused-import import boto3 import botocore # pylint: enable=unused-import # TODO Version check using salt.utils.versions from botocore.exceptions import ClientError logging.getLogger('boto3').setLevel(logging.CRITICAL) HAS_BOTO = True except ImportError: HAS_BOTO = False def __virtual__(): ''' Only load if boto3 libraries exist. ''' has_boto_reqs = salt.utils.versions.check_boto_reqs() if has_boto_reqs is True: __utils__['boto3.assign_funcs'](__name__, 'elbv2') return has_boto_reqs def create_target_group(name, protocol, port, vpc_id, region=None, key=None, keyid=None, profile=None, health_check_protocol='HTTP', health_check_port='traffic-port', health_check_path='/', health_check_interval_seconds=30, health_check_timeout_seconds=5, healthy_threshold_count=5, unhealthy_threshold_count=2): ''' Create target group if not present. name (string) - The name of the target group. protocol (string) - The protocol to use for routing traffic to the targets port (int) - The port on which the targets receive traffic. This port is used unless you specify a port override when registering the traffic. vpc_id (string) - The identifier of the virtual private cloud (VPC). health_check_protocol (string) - The protocol the load balancer uses when performing health check on targets. The default is the HTTP protocol. health_check_port (string) - The port the load balancer uses when performing health checks on targets. The default is 'traffic-port', which indicates the port on which each target receives traffic from the load balancer. health_check_path (string) - The ping path that is the destination on the targets for health checks. The default is /. health_check_interval_seconds (integer) - The approximate amount of time, in seconds, between health checks of an individual target. The default is 30 seconds. health_check_timeout_seconds (integer) - The amount of time, in seconds, during which no response from a target means a failed health check. The default is 5 seconds. healthy_threshold_count (integer) - The number of consecutive health checks successes required before considering an unhealthy target healthy. The default is 5. unhealthy_threshold_count (integer) - The number of consecutive health check failures required before considering a target unhealthy. The default is 2. returns (bool) - True on success, False on failure. CLI example: .. code-block:: bash salt myminion boto_elbv2.create_target_group learn1give1 protocol=HTTP port=54006 vpc_id=vpc-deadbeef ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if target_group_exists(name, region, key, keyid, profile): return True try: alb = conn.create_target_group(Name=name, Protocol=protocol, Port=port, VpcId=vpc_id, HealthCheckProtocol=health_check_protocol, HealthCheckPort=health_check_port, HealthCheckPath=health_check_path, HealthCheckIntervalSeconds=health_check_interval_seconds, HealthCheckTimeoutSeconds=health_check_timeout_seconds, HealthyThresholdCount=healthy_threshold_count, UnhealthyThresholdCount=unhealthy_threshold_count) if alb: log.info('Created ALB %s: %s', name, alb['TargetGroups'][0]['TargetGroupArn']) return True else: log.error('Failed to create ALB %s', name) return False except ClientError as error: log.error( 'Failed to create ALB %s: %s: %s', name, error.response['Error']['Code'], error.response['Error']['Message'], exc_info_on_loglevel=logging.DEBUG ) def delete_target_group(name, region=None, key=None, keyid=None, profile=None): ''' Delete target group. name (string) - Target Group Name or Amazon Resource Name (ARN). returns (bool) - True on success, False on failure. CLI example: .. code-block:: bash salt myminion boto_elbv2.delete_target_group arn:aws:elasticloadbalancing:us-west-2:644138682826:targetgroup/learn1give1-api/414788a16b5cf163 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not target_group_exists(name, region, key, keyid, profile): return True try: if name.startswith('arn:aws:elasticloadbalancing'): conn.delete_target_group(TargetGroupArn=name) log.info('Deleted target group %s', name) else: tg_info = conn.describe_target_groups(Names=[name]) if len(tg_info['TargetGroups']) != 1: return False arn = tg_info['TargetGroups'][0]['TargetGroupArn'] conn.delete_target_group(TargetGroupArn=arn) log.info('Deleted target group %s ARN %s', name, arn) return True except ClientError as error: log.error('Failed to delete target group %s', name, exc_info_on_loglevel=logging.DEBUG) return False def target_group_exists(name, region=None, key=None, keyid=None, profile=None): ''' Check to see if an target group exists. CLI example: .. code-block:: bash salt myminion boto_elbv2.target_group_exists arn:aws:elasticloadbalancing:us-west-2:644138682826:targetgroup/learn1give1-api/414788a16b5cf163 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: if name.startswith('arn:aws:elasticloadbalancing'): alb = conn.describe_target_groups(TargetGroupArns=[name]) else: alb = conn.describe_target_groups(Names=[name]) if alb: return True else: log.warning('The target group does not exist in region %s', region) return False except ClientError as error: log.warning('target_group_exists check for %s returned: %s', name, error) return False def describe_target_health(name, targets=None, region=None, key=None, keyid=None, profile=None): ''' Get the curret health check status for targets in a target group. CLI example: .. code-block:: bash salt myminion boto_elbv2.describe_target_health arn:aws:elasticloadbalancing:us-west-2:644138682826:targetgroup/learn1give1-api/414788a16b5cf163 targets=["i-isdf23ifjf"] ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: if targets: targetsdict = [] for target in targets: targetsdict.append({"Id": target}) instances = conn.describe_target_health(TargetGroupArn=name, Targets=targetsdict) else: instances = conn.describe_target_health(TargetGroupArn=name) ret = {} for instance in instances['TargetHealthDescriptions']: ret.update({instance['Target']['Id']: instance['TargetHealth']['State']}) return ret except ClientError as error: log.warning(error) return {} def register_targets(name, targets, region=None, key=None, keyid=None, profile=None): ''' Register targets to a target froup of an ALB. ``targets`` is either a instance id string or a list of instance id's. Returns: - ``True``: instance(s) registered successfully - ``False``: instance(s) failed to be registered CLI example: .. code-block:: bash salt myminion boto_elbv2.register_targets myelb instance_id salt myminion boto_elbv2.register_targets myelb "[instance_id,instance_id]" ''' targetsdict = [] if isinstance(targets, six.string_types) or isinstance(targets, six.text_type): targetsdict.append({"Id": targets}) else: for target in targets: targetsdict.append({"Id": target}) conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: registered_targets = conn.register_targets(TargetGroupArn=name, Targets=targetsdict) if registered_targets: return True return False except ClientError as error: log.warning(error) return False def deregister_targets(name, targets, region=None, key=None, keyid=None, profile=None): ''' Deregister targets to a target froup of an ALB. ``targets`` is either a instance id string or a list of instance id's. Returns: - ``True``: instance(s) deregistered successfully - ``False``: instance(s) failed to be deregistered CLI example: .. code-block:: bash salt myminion boto_elbv2.deregister_targets myelb instance_id salt myminion boto_elbv2.deregister_targets myelb "[instance_id,instance_id]" ''' targetsdict = [] if isinstance(targets, six.string_types) or isinstance(targets, six.text_type): targetsdict.append({"Id": targets}) else: for target in targets: targetsdict.append({"Id": target}) conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: registered_targets = conn.deregister_targets(TargetGroupArn=name, Targets=targetsdict) if registered_targets: return True return False except ClientError as error: log.warning(error) return False def describe_target_groups(names=None, target_group_arns=None, load_balancer_arn=None, region=None, key=None, keyid=None, profile=None): ''' Describes the specified target groups or all of your target groups. By default, all target groups are described. Alternatively, you can specify one of the following to filter the results: the ARN of the load balancer, the names of one or more target groups, or the ARNs of one or more target groups. Returns: list CLI example: .. code-block:: bash salt myminion boto_elbv2.describe_target_groups salt myminion boto_elbv2.describe_target_groups target_group_name salt myminion boto_elbv2.describe_target_groups "[tg_name,tg_name]" ''' if names and target_group_arns: raise SaltInvocationError('At most one of names or target_group_arns may ' 'be provided') if names: target_groups = names elif target_group_arns: target_groups = target_group_arns else: target_groups = None tg_list = [] if target_groups: if isinstance(target_groups, str) or isinstance(target_groups, six.text_type): tg_list.append(target_groups) else: for group in target_groups: tg_list.append(group) conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: if names: ret = conn.describe_target_groups(Names=tg_list)['TargetGroups'] elif target_group_arns: ret = conn.describe_target_groups(TargetGroupArns=tg_list)['TargetGroups'] elif load_balancer_arn: ret = conn.describe_target_groups(LoadBalancerArn=load_balancer_arn)['TargetGroups'] else: ret = [] next_marker = '' while True: r = conn.describe_target_groups(Marker=next_marker) for alb in r['TargetGroups']: ret.append(alb) if 'NextMarker' in r: next_marker = r['NextMarker'] else: break return ret if ret else [] except ClientError as error: log.warning(error) return False
saltstack/salt
salt/modules/boto_elbv2.py
describe_target_groups
python
def describe_target_groups(names=None, target_group_arns=None, load_balancer_arn=None, region=None, key=None, keyid=None, profile=None): ''' Describes the specified target groups or all of your target groups. By default, all target groups are described. Alternatively, you can specify one of the following to filter the results: the ARN of the load balancer, the names of one or more target groups, or the ARNs of one or more target groups. Returns: list CLI example: .. code-block:: bash salt myminion boto_elbv2.describe_target_groups salt myminion boto_elbv2.describe_target_groups target_group_name salt myminion boto_elbv2.describe_target_groups "[tg_name,tg_name]" ''' if names and target_group_arns: raise SaltInvocationError('At most one of names or target_group_arns may ' 'be provided') if names: target_groups = names elif target_group_arns: target_groups = target_group_arns else: target_groups = None tg_list = [] if target_groups: if isinstance(target_groups, str) or isinstance(target_groups, six.text_type): tg_list.append(target_groups) else: for group in target_groups: tg_list.append(group) conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: if names: ret = conn.describe_target_groups(Names=tg_list)['TargetGroups'] elif target_group_arns: ret = conn.describe_target_groups(TargetGroupArns=tg_list)['TargetGroups'] elif load_balancer_arn: ret = conn.describe_target_groups(LoadBalancerArn=load_balancer_arn)['TargetGroups'] else: ret = [] next_marker = '' while True: r = conn.describe_target_groups(Marker=next_marker) for alb in r['TargetGroups']: ret.append(alb) if 'NextMarker' in r: next_marker = r['NextMarker'] else: break return ret if ret else [] except ClientError as error: log.warning(error) return False
Describes the specified target groups or all of your target groups. By default, all target groups are described. Alternatively, you can specify one of the following to filter the results: the ARN of the load balancer, the names of one or more target groups, or the ARNs of one or more target groups. Returns: list CLI example: .. code-block:: bash salt myminion boto_elbv2.describe_target_groups salt myminion boto_elbv2.describe_target_groups target_group_name salt myminion boto_elbv2.describe_target_groups "[tg_name,tg_name]"
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_elbv2.py#L417-L482
null
# -*- coding: utf-8 -*- ''' Connection module for Amazon ALB .. versionadded:: 2017.7.0 :configuration: This module accepts explicit elb credentials but can also utilize IAM roles assigned to the instance through Instance Profiles. Dynamic credentials are then automatically obtained from AWS API and no further configuration is necessary. More Information available at: .. code-block:: text http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/iam-roles-for-amazon-ec2.html If IAM roles are not used you need to specify them either in a pillar or in the minion's config file: .. code-block:: yaml elbv2.keyid: GKTADJGHEIQSXMKKRBJ08H elbv2.key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs elbv2.region: us-west-2 If a region is not specified, the default is us-east-1. It's also possible to specify key, keyid and region via a profile, either as a passed in dict, or as a string to pull from pillars or minion config: .. code-block:: yaml myprofile: keyid: GKTADJGHEIQSXMKKRBJ08H key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs region: us-east-1 :depends: boto3 ''' # keep lint from choking on _get_conn and _cache_id # pylint: disable=E0602 from __future__ import absolute_import, print_function, unicode_literals # Import Python libs import logging log = logging.getLogger(__name__) # Import Salt libs from salt.ext import six import salt.utils.versions # Import third-party libs try: # pylint: disable=unused-import import boto3 import botocore # pylint: enable=unused-import # TODO Version check using salt.utils.versions from botocore.exceptions import ClientError logging.getLogger('boto3').setLevel(logging.CRITICAL) HAS_BOTO = True except ImportError: HAS_BOTO = False def __virtual__(): ''' Only load if boto3 libraries exist. ''' has_boto_reqs = salt.utils.versions.check_boto_reqs() if has_boto_reqs is True: __utils__['boto3.assign_funcs'](__name__, 'elbv2') return has_boto_reqs def create_target_group(name, protocol, port, vpc_id, region=None, key=None, keyid=None, profile=None, health_check_protocol='HTTP', health_check_port='traffic-port', health_check_path='/', health_check_interval_seconds=30, health_check_timeout_seconds=5, healthy_threshold_count=5, unhealthy_threshold_count=2): ''' Create target group if not present. name (string) - The name of the target group. protocol (string) - The protocol to use for routing traffic to the targets port (int) - The port on which the targets receive traffic. This port is used unless you specify a port override when registering the traffic. vpc_id (string) - The identifier of the virtual private cloud (VPC). health_check_protocol (string) - The protocol the load balancer uses when performing health check on targets. The default is the HTTP protocol. health_check_port (string) - The port the load balancer uses when performing health checks on targets. The default is 'traffic-port', which indicates the port on which each target receives traffic from the load balancer. health_check_path (string) - The ping path that is the destination on the targets for health checks. The default is /. health_check_interval_seconds (integer) - The approximate amount of time, in seconds, between health checks of an individual target. The default is 30 seconds. health_check_timeout_seconds (integer) - The amount of time, in seconds, during which no response from a target means a failed health check. The default is 5 seconds. healthy_threshold_count (integer) - The number of consecutive health checks successes required before considering an unhealthy target healthy. The default is 5. unhealthy_threshold_count (integer) - The number of consecutive health check failures required before considering a target unhealthy. The default is 2. returns (bool) - True on success, False on failure. CLI example: .. code-block:: bash salt myminion boto_elbv2.create_target_group learn1give1 protocol=HTTP port=54006 vpc_id=vpc-deadbeef ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if target_group_exists(name, region, key, keyid, profile): return True try: alb = conn.create_target_group(Name=name, Protocol=protocol, Port=port, VpcId=vpc_id, HealthCheckProtocol=health_check_protocol, HealthCheckPort=health_check_port, HealthCheckPath=health_check_path, HealthCheckIntervalSeconds=health_check_interval_seconds, HealthCheckTimeoutSeconds=health_check_timeout_seconds, HealthyThresholdCount=healthy_threshold_count, UnhealthyThresholdCount=unhealthy_threshold_count) if alb: log.info('Created ALB %s: %s', name, alb['TargetGroups'][0]['TargetGroupArn']) return True else: log.error('Failed to create ALB %s', name) return False except ClientError as error: log.error( 'Failed to create ALB %s: %s: %s', name, error.response['Error']['Code'], error.response['Error']['Message'], exc_info_on_loglevel=logging.DEBUG ) def delete_target_group(name, region=None, key=None, keyid=None, profile=None): ''' Delete target group. name (string) - Target Group Name or Amazon Resource Name (ARN). returns (bool) - True on success, False on failure. CLI example: .. code-block:: bash salt myminion boto_elbv2.delete_target_group arn:aws:elasticloadbalancing:us-west-2:644138682826:targetgroup/learn1give1-api/414788a16b5cf163 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not target_group_exists(name, region, key, keyid, profile): return True try: if name.startswith('arn:aws:elasticloadbalancing'): conn.delete_target_group(TargetGroupArn=name) log.info('Deleted target group %s', name) else: tg_info = conn.describe_target_groups(Names=[name]) if len(tg_info['TargetGroups']) != 1: return False arn = tg_info['TargetGroups'][0]['TargetGroupArn'] conn.delete_target_group(TargetGroupArn=arn) log.info('Deleted target group %s ARN %s', name, arn) return True except ClientError as error: log.error('Failed to delete target group %s', name, exc_info_on_loglevel=logging.DEBUG) return False def target_group_exists(name, region=None, key=None, keyid=None, profile=None): ''' Check to see if an target group exists. CLI example: .. code-block:: bash salt myminion boto_elbv2.target_group_exists arn:aws:elasticloadbalancing:us-west-2:644138682826:targetgroup/learn1give1-api/414788a16b5cf163 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: if name.startswith('arn:aws:elasticloadbalancing'): alb = conn.describe_target_groups(TargetGroupArns=[name]) else: alb = conn.describe_target_groups(Names=[name]) if alb: return True else: log.warning('The target group does not exist in region %s', region) return False except ClientError as error: log.warning('target_group_exists check for %s returned: %s', name, error) return False def describe_target_health(name, targets=None, region=None, key=None, keyid=None, profile=None): ''' Get the curret health check status for targets in a target group. CLI example: .. code-block:: bash salt myminion boto_elbv2.describe_target_health arn:aws:elasticloadbalancing:us-west-2:644138682826:targetgroup/learn1give1-api/414788a16b5cf163 targets=["i-isdf23ifjf"] ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: if targets: targetsdict = [] for target in targets: targetsdict.append({"Id": target}) instances = conn.describe_target_health(TargetGroupArn=name, Targets=targetsdict) else: instances = conn.describe_target_health(TargetGroupArn=name) ret = {} for instance in instances['TargetHealthDescriptions']: ret.update({instance['Target']['Id']: instance['TargetHealth']['State']}) return ret except ClientError as error: log.warning(error) return {} def register_targets(name, targets, region=None, key=None, keyid=None, profile=None): ''' Register targets to a target froup of an ALB. ``targets`` is either a instance id string or a list of instance id's. Returns: - ``True``: instance(s) registered successfully - ``False``: instance(s) failed to be registered CLI example: .. code-block:: bash salt myminion boto_elbv2.register_targets myelb instance_id salt myminion boto_elbv2.register_targets myelb "[instance_id,instance_id]" ''' targetsdict = [] if isinstance(targets, six.string_types) or isinstance(targets, six.text_type): targetsdict.append({"Id": targets}) else: for target in targets: targetsdict.append({"Id": target}) conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: registered_targets = conn.register_targets(TargetGroupArn=name, Targets=targetsdict) if registered_targets: return True return False except ClientError as error: log.warning(error) return False def deregister_targets(name, targets, region=None, key=None, keyid=None, profile=None): ''' Deregister targets to a target froup of an ALB. ``targets`` is either a instance id string or a list of instance id's. Returns: - ``True``: instance(s) deregistered successfully - ``False``: instance(s) failed to be deregistered CLI example: .. code-block:: bash salt myminion boto_elbv2.deregister_targets myelb instance_id salt myminion boto_elbv2.deregister_targets myelb "[instance_id,instance_id]" ''' targetsdict = [] if isinstance(targets, six.string_types) or isinstance(targets, six.text_type): targetsdict.append({"Id": targets}) else: for target in targets: targetsdict.append({"Id": target}) conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: registered_targets = conn.deregister_targets(TargetGroupArn=name, Targets=targetsdict) if registered_targets: return True return False except ClientError as error: log.warning(error) return False def describe_load_balancers(names=None, load_balancer_arns=None, region=None, key=None, keyid=None, profile=None): ''' Describes the specified load balancer or all of your load balancers. Returns: list CLI example: .. code-block:: bash salt myminion boto_elbv2.describe_load_balancers salt myminion boto_elbv2.describe_load_balancers alb_name salt myminion boto_elbv2.describe_load_balancers "[alb_name,alb_name]" ''' if names and load_balancer_arns: raise SaltInvocationError('At most one of names or load_balancer_arns may ' 'be provided') if names: albs = names elif load_balancer_arns: albs = load_balancer_arns else: albs = None albs_list = [] if albs: if isinstance(albs, str) or isinstance(albs, six.text_type): albs_list.append(albs) else: for alb in albs: albs_list.append(alb) conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: if names: ret = conn.describe_load_balancers(Names=albs_list)['LoadBalancers'] elif load_balancer_arns: ret = conn.describe_load_balancers(LoadBalancerArns=albs_list)['LoadBalancers'] else: ret = [] next_marker = '' while True: r = conn.describe_load_balancers(Marker=next_marker) for alb in r['LoadBalancers']: ret.append(alb) if 'NextMarker' in r: next_marker = r['NextMarker'] else: break return ret if ret else [] except ClientError as error: log.warning(error) return False
saltstack/salt
salt/modules/boto_ssm.py
get_parameter
python
def get_parameter(name, withdecryption=False, resp_json=False, region=None, key=None, keyid=None, profile=None): ''' Retrives a parameter from SSM Parameter Store .. versionadded:: Neon .. code-block:: text salt-call boto_ssm.get_parameter test-param withdescription=True ''' conn = __utils__['boto3.get_connection']('ssm', region=region, key=key, keyid=keyid, profile=profile) try: resp = conn.get_parameter(Name=name, WithDecryption=withdecryption) except conn.exceptions.ParameterNotFound: log.warning("get_parameter: Unable to locate name: %s", name) return False if resp_json: return json.loads(resp['Parameter']['Value']) else: return resp['Parameter']['Value']
Retrives a parameter from SSM Parameter Store .. versionadded:: Neon .. code-block:: text salt-call boto_ssm.get_parameter test-param withdescription=True
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_ssm.py#L37-L57
[ "def loads(s, **kwargs):\n '''\n .. versionadded:: 2018.3.0\n\n Wraps json.loads and prevents a traceback in the event that a bytestring is\n passed to the function. (Python < 3.6 cannot load bytestrings)\n\n You can pass an alternate json module (loaded via import_json() above)\n using the _json_module argument)\n '''\n json_module = kwargs.pop('_json_module', json)\n try:\n return json_module.loads(s, **kwargs)\n except TypeError as exc:\n # json.loads cannot load bytestrings in Python < 3.6\n if six.PY3 and isinstance(s, bytes):\n return json_module.loads(salt.utils.stringutils.to_unicode(s), **kwargs)\n else:\n raise exc\n" ]
# -*- coding: utf-8 -*- ''' Connection module for Amazon SSM :configuration: This module uses IAM roles assigned to the instance through Instance Profiles. Dynamic credentials are then automatically obtained from AWS API and no further configuration is necessary. More Information available at: .. code-block:: text http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/iam-roles-for-amazon-ec2.html :depends: boto3 ''' # Import Python libs from __future__ import absolute_import, print_function, unicode_literals import logging # Import Salt libs import salt.utils.versions import salt.utils.json as json log = logging.getLogger(__name__) def __virtual__(): ''' Only load if boto libraries exist. ''' has_boto_reqs = salt.utils.versions.check_boto_reqs() if has_boto_reqs is True: __utils__['boto3.assign_funcs'](__name__, 'ssm') return has_boto_reqs def put_parameter(Name, Value, Description=None, Type='String', KeyId=None, Overwrite=False, AllowedPattern=None, region=None, key=None, keyid=None, profile=None): ''' Sets a parameter in the SSM parameter store .. versionadded:: Neon .. code-block:: text salt-call boto_ssm.put_parameter test-param test_value Type=SecureString KeyId=alias/aws/ssm Description='test encrypted key' ''' conn = __utils__['boto3.get_connection']('ssm', region=region, key=key, keyid=keyid, profile=profile) if Type not in ('String', 'StringList', 'SecureString'): raise AssertionError('Type needs to be String|StringList|SecureString') if Type == 'SecureString' and not KeyId: raise AssertionError('Require KeyId with SecureString') boto_args = {} if Description: boto_args['Description'] = Description if KeyId: boto_args['KeyId'] = KeyId if AllowedPattern: boto_args['AllowedPattern'] = AllowedPattern try: resp = conn.put_parameter(Name=Name, Value=Value, Type=Type, Overwrite=Overwrite, **boto_args) except conn.exceptions.ParameterAlreadyExists: log.warning("The parameter already exists." " To overwrite this value, set the Overwrite option in the request to True") return False return resp['Version'] def delete_parameter(Name, region=None, key=None, keyid=None, profile=None): ''' Removes a parameter from the SSM parameter store .. versionadded:: Neon .. code-block:: text salt-call boto_ssm.delete_parameter test-param ''' conn = __utils__['boto3.get_connection']('ssm', region=region, key=key, keyid=keyid, profile=profile) try: resp = conn.delete_parameter(Name=Name) except conn.exceptions.ParameterNotFound: log.warning("delete_parameter: Unable to locate name: %s", Name) return False if resp['ResponseMetadata']['HTTPStatusCode'] == 200: return True else: return False
saltstack/salt
salt/modules/boto_ssm.py
put_parameter
python
def put_parameter(Name, Value, Description=None, Type='String', KeyId=None, Overwrite=False, AllowedPattern=None, region=None, key=None, keyid=None, profile=None): ''' Sets a parameter in the SSM parameter store .. versionadded:: Neon .. code-block:: text salt-call boto_ssm.put_parameter test-param test_value Type=SecureString KeyId=alias/aws/ssm Description='test encrypted key' ''' conn = __utils__['boto3.get_connection']('ssm', region=region, key=key, keyid=keyid, profile=profile) if Type not in ('String', 'StringList', 'SecureString'): raise AssertionError('Type needs to be String|StringList|SecureString') if Type == 'SecureString' and not KeyId: raise AssertionError('Require KeyId with SecureString') boto_args = {} if Description: boto_args['Description'] = Description if KeyId: boto_args['KeyId'] = KeyId if AllowedPattern: boto_args['AllowedPattern'] = AllowedPattern try: resp = conn.put_parameter(Name=Name, Value=Value, Type=Type, Overwrite=Overwrite, **boto_args) except conn.exceptions.ParameterAlreadyExists: log.warning("The parameter already exists." " To overwrite this value, set the Overwrite option in the request to True") return False return resp['Version']
Sets a parameter in the SSM parameter store .. versionadded:: Neon .. code-block:: text salt-call boto_ssm.put_parameter test-param test_value Type=SecureString KeyId=alias/aws/ssm Description='test encrypted key'
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_ssm.py#L60-L100
null
# -*- coding: utf-8 -*- ''' Connection module for Amazon SSM :configuration: This module uses IAM roles assigned to the instance through Instance Profiles. Dynamic credentials are then automatically obtained from AWS API and no further configuration is necessary. More Information available at: .. code-block:: text http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/iam-roles-for-amazon-ec2.html :depends: boto3 ''' # Import Python libs from __future__ import absolute_import, print_function, unicode_literals import logging # Import Salt libs import salt.utils.versions import salt.utils.json as json log = logging.getLogger(__name__) def __virtual__(): ''' Only load if boto libraries exist. ''' has_boto_reqs = salt.utils.versions.check_boto_reqs() if has_boto_reqs is True: __utils__['boto3.assign_funcs'](__name__, 'ssm') return has_boto_reqs def get_parameter(name, withdecryption=False, resp_json=False, region=None, key=None, keyid=None, profile=None): ''' Retrives a parameter from SSM Parameter Store .. versionadded:: Neon .. code-block:: text salt-call boto_ssm.get_parameter test-param withdescription=True ''' conn = __utils__['boto3.get_connection']('ssm', region=region, key=key, keyid=keyid, profile=profile) try: resp = conn.get_parameter(Name=name, WithDecryption=withdecryption) except conn.exceptions.ParameterNotFound: log.warning("get_parameter: Unable to locate name: %s", name) return False if resp_json: return json.loads(resp['Parameter']['Value']) else: return resp['Parameter']['Value'] def delete_parameter(Name, region=None, key=None, keyid=None, profile=None): ''' Removes a parameter from the SSM parameter store .. versionadded:: Neon .. code-block:: text salt-call boto_ssm.delete_parameter test-param ''' conn = __utils__['boto3.get_connection']('ssm', region=region, key=key, keyid=keyid, profile=profile) try: resp = conn.delete_parameter(Name=Name) except conn.exceptions.ParameterNotFound: log.warning("delete_parameter: Unable to locate name: %s", Name) return False if resp['ResponseMetadata']['HTTPStatusCode'] == 200: return True else: return False
saltstack/salt
salt/modules/boto_ssm.py
delete_parameter
python
def delete_parameter(Name, region=None, key=None, keyid=None, profile=None): ''' Removes a parameter from the SSM parameter store .. versionadded:: Neon .. code-block:: text salt-call boto_ssm.delete_parameter test-param ''' conn = __utils__['boto3.get_connection']('ssm', region=region, key=key, keyid=keyid, profile=profile) try: resp = conn.delete_parameter(Name=Name) except conn.exceptions.ParameterNotFound: log.warning("delete_parameter: Unable to locate name: %s", Name) return False if resp['ResponseMetadata']['HTTPStatusCode'] == 200: return True else: return False
Removes a parameter from the SSM parameter store .. versionadded:: Neon .. code-block:: text salt-call boto_ssm.delete_parameter test-param
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_ssm.py#L103-L121
null
# -*- coding: utf-8 -*- ''' Connection module for Amazon SSM :configuration: This module uses IAM roles assigned to the instance through Instance Profiles. Dynamic credentials are then automatically obtained from AWS API and no further configuration is necessary. More Information available at: .. code-block:: text http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/iam-roles-for-amazon-ec2.html :depends: boto3 ''' # Import Python libs from __future__ import absolute_import, print_function, unicode_literals import logging # Import Salt libs import salt.utils.versions import salt.utils.json as json log = logging.getLogger(__name__) def __virtual__(): ''' Only load if boto libraries exist. ''' has_boto_reqs = salt.utils.versions.check_boto_reqs() if has_boto_reqs is True: __utils__['boto3.assign_funcs'](__name__, 'ssm') return has_boto_reqs def get_parameter(name, withdecryption=False, resp_json=False, region=None, key=None, keyid=None, profile=None): ''' Retrives a parameter from SSM Parameter Store .. versionadded:: Neon .. code-block:: text salt-call boto_ssm.get_parameter test-param withdescription=True ''' conn = __utils__['boto3.get_connection']('ssm', region=region, key=key, keyid=keyid, profile=profile) try: resp = conn.get_parameter(Name=name, WithDecryption=withdecryption) except conn.exceptions.ParameterNotFound: log.warning("get_parameter: Unable to locate name: %s", name) return False if resp_json: return json.loads(resp['Parameter']['Value']) else: return resp['Parameter']['Value'] def put_parameter(Name, Value, Description=None, Type='String', KeyId=None, Overwrite=False, AllowedPattern=None, region=None, key=None, keyid=None, profile=None): ''' Sets a parameter in the SSM parameter store .. versionadded:: Neon .. code-block:: text salt-call boto_ssm.put_parameter test-param test_value Type=SecureString KeyId=alias/aws/ssm Description='test encrypted key' ''' conn = __utils__['boto3.get_connection']('ssm', region=region, key=key, keyid=keyid, profile=profile) if Type not in ('String', 'StringList', 'SecureString'): raise AssertionError('Type needs to be String|StringList|SecureString') if Type == 'SecureString' and not KeyId: raise AssertionError('Require KeyId with SecureString') boto_args = {} if Description: boto_args['Description'] = Description if KeyId: boto_args['KeyId'] = KeyId if AllowedPattern: boto_args['AllowedPattern'] = AllowedPattern try: resp = conn.put_parameter(Name=Name, Value=Value, Type=Type, Overwrite=Overwrite, **boto_args) except conn.exceptions.ParameterAlreadyExists: log.warning("The parameter already exists." " To overwrite this value, set the Overwrite option in the request to True") return False return resp['Version']
saltstack/salt
salt/utils/hashutils.py
base64_b64encode
python
def base64_b64encode(instr): ''' Encode a string as base64 using the "modern" Python interface. Among other possible differences, the "modern" encoder does not include newline ('\\n') characters in the encoded output. ''' return salt.utils.stringutils.to_unicode( base64.b64encode(salt.utils.stringutils.to_bytes(instr)), encoding='utf8' if salt.utils.platform.is_windows() else None )
Encode a string as base64 using the "modern" Python interface. Among other possible differences, the "modern" encoder does not include newline ('\\n') characters in the encoded output.
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/hashutils.py#L24-L34
[ "def to_unicode(s, encoding=None, errors='strict', normalize=False):\n '''\n Given str or unicode, return unicode (str for python 3)\n '''\n def _normalize(s):\n return unicodedata.normalize('NFC', s) if normalize else s\n\n if encoding is None:\n # Try utf-8 first, and fall back to detected encoding\n encoding = ('utf-8', __salt_system_encoding__)\n if not isinstance(encoding, (tuple, list)):\n encoding = (encoding,)\n\n if not encoding:\n raise ValueError('encoding cannot be empty')\n\n exc = None\n if six.PY3:\n if isinstance(s, str):\n return _normalize(s)\n elif isinstance(s, (bytes, bytearray)):\n return _normalize(to_str(s, encoding, errors))\n raise TypeError('expected str, bytes, or bytearray')\n else:\n # This needs to be str and not six.string_types, since if the string is\n # already a unicode type, it does not need to be decoded (and doing so\n # will raise an exception).\n if isinstance(s, unicode): # pylint: disable=incompatible-py3-code,undefined-variable\n return _normalize(s)\n elif isinstance(s, (str, bytearray)):\n for enc in encoding:\n try:\n return _normalize(s.decode(enc, errors))\n except UnicodeDecodeError as err:\n exc = err\n continue\n # The only way we get this far is if a UnicodeDecodeError was\n # raised, otherwise we would have already returned (or raised some\n # other exception).\n raise exc # pylint: disable=raising-bad-type\n raise TypeError('expected str or bytearray')\n" ]
# encoding: utf-8 ''' A collection of hashing and encoding utils. ''' from __future__ import absolute_import, unicode_literals, print_function # Import python libs import base64 import hashlib import hmac import random import os # Import Salt libs from salt.ext import six import salt.utils.files import salt.utils.platform import salt.utils.stringutils from salt.utils.decorators.jinja import jinja_filter @jinja_filter('base64_encode') @jinja_filter('base64_decode') def base64_b64decode(instr): ''' Decode a base64-encoded string using the "modern" Python interface. ''' decoded = base64.b64decode(salt.utils.stringutils.to_bytes(instr)) try: return salt.utils.stringutils.to_unicode( decoded, encoding='utf8' if salt.utils.platform.is_windows() else None ) except UnicodeDecodeError: return decoded def base64_encodestring(instr): ''' Encode a string as base64 using the "legacy" Python interface. Among other possible differences, the "legacy" encoder includes a newline ('\\n') character after every 76 characters and always at the end of the encoded string. ''' return salt.utils.stringutils.to_unicode( base64.encodestring(salt.utils.stringutils.to_bytes(instr)), encoding='utf8' if salt.utils.platform.is_windows() else None ) def base64_decodestring(instr): ''' Decode a base64-encoded string using the "legacy" Python interface. ''' b = salt.utils.stringutils.to_bytes(instr) try: # PY3 decoded = base64.decodebytes(b) except AttributeError: # PY2 decoded = base64.decodestring(b) try: return salt.utils.stringutils.to_unicode( decoded, encoding='utf8' if salt.utils.platform.is_windows() else None ) except UnicodeDecodeError: return decoded @jinja_filter('md5') def md5_digest(instr): ''' Generate an md5 hash of a given string. ''' return salt.utils.stringutils.to_unicode( hashlib.md5(salt.utils.stringutils.to_bytes(instr)).hexdigest() ) def sha1_digest(instr): ''' Generate an sha1 hash of a given string. ''' if six.PY3: b = salt.utils.stringutils.to_bytes(instr) return hashlib.sha1(b).hexdigest() return hashlib.sha1(instr).hexdigest() @jinja_filter('sha256') def sha256_digest(instr): ''' Generate a sha256 hash of a given string. ''' return salt.utils.stringutils.to_unicode( hashlib.sha256(salt.utils.stringutils.to_bytes(instr)).hexdigest() ) @jinja_filter('sha512') def sha512_digest(instr): ''' Generate a sha512 hash of a given string ''' return salt.utils.stringutils.to_unicode( hashlib.sha512(salt.utils.stringutils.to_bytes(instr)).hexdigest() ) @jinja_filter('hmac') def hmac_signature(string, shared_secret, challenge_hmac): ''' Verify a challenging hmac signature against a string / shared-secret Returns a boolean if the verification succeeded or failed. ''' msg = salt.utils.stringutils.to_bytes(string) key = salt.utils.stringutils.to_bytes(shared_secret) challenge = salt.utils.stringutils.to_bytes(challenge_hmac) hmac_hash = hmac.new(key, msg, hashlib.sha256) valid_hmac = base64.b64encode(hmac_hash.digest()) return valid_hmac == challenge @jinja_filter('random_hash') def random_hash(size=9999999999, hash_type=None): ''' Return a hash of a randomized data from random.SystemRandom() ''' if not hash_type: hash_type = 'md5' hasher = getattr(hashlib, hash_type) return hasher(salt.utils.stringutils.to_bytes(six.text_type(random.SystemRandom().randint(0, size)))).hexdigest() @jinja_filter('file_hashsum') def get_hash(path, form='sha256', chunk_size=65536): ''' Get the hash sum of a file This is better than ``get_sum`` for the following reasons: - It does not read the entire file into memory. - It does not return a string on error. The returned value of ``get_sum`` cannot really be trusted since it is vulnerable to collisions: ``get_sum(..., 'xyz') == 'Hash xyz not supported'`` ''' hash_type = hasattr(hashlib, form) and getattr(hashlib, form) or None if hash_type is None: raise ValueError('Invalid hash type: {0}'.format(form)) with salt.utils.files.fopen(path, 'rb') as ifile: hash_obj = hash_type() # read the file in in chunks, not the entire file for chunk in iter(lambda: ifile.read(chunk_size), b''): hash_obj.update(chunk) return hash_obj.hexdigest() class DigestCollector(object): ''' Class to collect digest of the file tree. ''' def __init__(self, form='sha256', buff=0x10000): ''' Constructor of the class. :param form: ''' self.__digest = hasattr(hashlib, form) and getattr(hashlib, form)() or None if self.__digest is None: raise ValueError('Invalid hash type: {0}'.format(form)) self.__buff = buff def add(self, path): ''' Update digest with the file content by path. :param path: :return: ''' with salt.utils.files.fopen(path, 'rb') as ifile: for chunk in iter(lambda: ifile.read(self.__buff), b''): self.__digest.update(chunk) def digest(self): ''' Get digest. :return: ''' return salt.utils.stringutils.to_str(self.__digest.hexdigest() + os.linesep)
saltstack/salt
salt/utils/hashutils.py
base64_b64decode
python
def base64_b64decode(instr): ''' Decode a base64-encoded string using the "modern" Python interface. ''' decoded = base64.b64decode(salt.utils.stringutils.to_bytes(instr)) try: return salt.utils.stringutils.to_unicode( decoded, encoding='utf8' if salt.utils.platform.is_windows() else None ) except UnicodeDecodeError: return decoded
Decode a base64-encoded string using the "modern" Python interface.
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/hashutils.py#L38-L49
[ "def to_unicode(s, encoding=None, errors='strict', normalize=False):\n '''\n Given str or unicode, return unicode (str for python 3)\n '''\n def _normalize(s):\n return unicodedata.normalize('NFC', s) if normalize else s\n\n if encoding is None:\n # Try utf-8 first, and fall back to detected encoding\n encoding = ('utf-8', __salt_system_encoding__)\n if not isinstance(encoding, (tuple, list)):\n encoding = (encoding,)\n\n if not encoding:\n raise ValueError('encoding cannot be empty')\n\n exc = None\n if six.PY3:\n if isinstance(s, str):\n return _normalize(s)\n elif isinstance(s, (bytes, bytearray)):\n return _normalize(to_str(s, encoding, errors))\n raise TypeError('expected str, bytes, or bytearray')\n else:\n # This needs to be str and not six.string_types, since if the string is\n # already a unicode type, it does not need to be decoded (and doing so\n # will raise an exception).\n if isinstance(s, unicode): # pylint: disable=incompatible-py3-code,undefined-variable\n return _normalize(s)\n elif isinstance(s, (str, bytearray)):\n for enc in encoding:\n try:\n return _normalize(s.decode(enc, errors))\n except UnicodeDecodeError as err:\n exc = err\n continue\n # The only way we get this far is if a UnicodeDecodeError was\n # raised, otherwise we would have already returned (or raised some\n # other exception).\n raise exc # pylint: disable=raising-bad-type\n raise TypeError('expected str or bytearray')\n" ]
# encoding: utf-8 ''' A collection of hashing and encoding utils. ''' from __future__ import absolute_import, unicode_literals, print_function # Import python libs import base64 import hashlib import hmac import random import os # Import Salt libs from salt.ext import six import salt.utils.files import salt.utils.platform import salt.utils.stringutils from salt.utils.decorators.jinja import jinja_filter @jinja_filter('base64_encode') def base64_b64encode(instr): ''' Encode a string as base64 using the "modern" Python interface. Among other possible differences, the "modern" encoder does not include newline ('\\n') characters in the encoded output. ''' return salt.utils.stringutils.to_unicode( base64.b64encode(salt.utils.stringutils.to_bytes(instr)), encoding='utf8' if salt.utils.platform.is_windows() else None ) @jinja_filter('base64_decode') def base64_encodestring(instr): ''' Encode a string as base64 using the "legacy" Python interface. Among other possible differences, the "legacy" encoder includes a newline ('\\n') character after every 76 characters and always at the end of the encoded string. ''' return salt.utils.stringutils.to_unicode( base64.encodestring(salt.utils.stringutils.to_bytes(instr)), encoding='utf8' if salt.utils.platform.is_windows() else None ) def base64_decodestring(instr): ''' Decode a base64-encoded string using the "legacy" Python interface. ''' b = salt.utils.stringutils.to_bytes(instr) try: # PY3 decoded = base64.decodebytes(b) except AttributeError: # PY2 decoded = base64.decodestring(b) try: return salt.utils.stringutils.to_unicode( decoded, encoding='utf8' if salt.utils.platform.is_windows() else None ) except UnicodeDecodeError: return decoded @jinja_filter('md5') def md5_digest(instr): ''' Generate an md5 hash of a given string. ''' return salt.utils.stringutils.to_unicode( hashlib.md5(salt.utils.stringutils.to_bytes(instr)).hexdigest() ) def sha1_digest(instr): ''' Generate an sha1 hash of a given string. ''' if six.PY3: b = salt.utils.stringutils.to_bytes(instr) return hashlib.sha1(b).hexdigest() return hashlib.sha1(instr).hexdigest() @jinja_filter('sha256') def sha256_digest(instr): ''' Generate a sha256 hash of a given string. ''' return salt.utils.stringutils.to_unicode( hashlib.sha256(salt.utils.stringutils.to_bytes(instr)).hexdigest() ) @jinja_filter('sha512') def sha512_digest(instr): ''' Generate a sha512 hash of a given string ''' return salt.utils.stringutils.to_unicode( hashlib.sha512(salt.utils.stringutils.to_bytes(instr)).hexdigest() ) @jinja_filter('hmac') def hmac_signature(string, shared_secret, challenge_hmac): ''' Verify a challenging hmac signature against a string / shared-secret Returns a boolean if the verification succeeded or failed. ''' msg = salt.utils.stringutils.to_bytes(string) key = salt.utils.stringutils.to_bytes(shared_secret) challenge = salt.utils.stringutils.to_bytes(challenge_hmac) hmac_hash = hmac.new(key, msg, hashlib.sha256) valid_hmac = base64.b64encode(hmac_hash.digest()) return valid_hmac == challenge @jinja_filter('random_hash') def random_hash(size=9999999999, hash_type=None): ''' Return a hash of a randomized data from random.SystemRandom() ''' if not hash_type: hash_type = 'md5' hasher = getattr(hashlib, hash_type) return hasher(salt.utils.stringutils.to_bytes(six.text_type(random.SystemRandom().randint(0, size)))).hexdigest() @jinja_filter('file_hashsum') def get_hash(path, form='sha256', chunk_size=65536): ''' Get the hash sum of a file This is better than ``get_sum`` for the following reasons: - It does not read the entire file into memory. - It does not return a string on error. The returned value of ``get_sum`` cannot really be trusted since it is vulnerable to collisions: ``get_sum(..., 'xyz') == 'Hash xyz not supported'`` ''' hash_type = hasattr(hashlib, form) and getattr(hashlib, form) or None if hash_type is None: raise ValueError('Invalid hash type: {0}'.format(form)) with salt.utils.files.fopen(path, 'rb') as ifile: hash_obj = hash_type() # read the file in in chunks, not the entire file for chunk in iter(lambda: ifile.read(chunk_size), b''): hash_obj.update(chunk) return hash_obj.hexdigest() class DigestCollector(object): ''' Class to collect digest of the file tree. ''' def __init__(self, form='sha256', buff=0x10000): ''' Constructor of the class. :param form: ''' self.__digest = hasattr(hashlib, form) and getattr(hashlib, form)() or None if self.__digest is None: raise ValueError('Invalid hash type: {0}'.format(form)) self.__buff = buff def add(self, path): ''' Update digest with the file content by path. :param path: :return: ''' with salt.utils.files.fopen(path, 'rb') as ifile: for chunk in iter(lambda: ifile.read(self.__buff), b''): self.__digest.update(chunk) def digest(self): ''' Get digest. :return: ''' return salt.utils.stringutils.to_str(self.__digest.hexdigest() + os.linesep)
saltstack/salt
salt/utils/hashutils.py
base64_encodestring
python
def base64_encodestring(instr): ''' Encode a string as base64 using the "legacy" Python interface. Among other possible differences, the "legacy" encoder includes a newline ('\\n') character after every 76 characters and always at the end of the encoded string. ''' return salt.utils.stringutils.to_unicode( base64.encodestring(salt.utils.stringutils.to_bytes(instr)), encoding='utf8' if salt.utils.platform.is_windows() else None )
Encode a string as base64 using the "legacy" Python interface. Among other possible differences, the "legacy" encoder includes a newline ('\\n') character after every 76 characters and always at the end of the encoded string.
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/hashutils.py#L52-L63
[ "def to_unicode(s, encoding=None, errors='strict', normalize=False):\n '''\n Given str or unicode, return unicode (str for python 3)\n '''\n def _normalize(s):\n return unicodedata.normalize('NFC', s) if normalize else s\n\n if encoding is None:\n # Try utf-8 first, and fall back to detected encoding\n encoding = ('utf-8', __salt_system_encoding__)\n if not isinstance(encoding, (tuple, list)):\n encoding = (encoding,)\n\n if not encoding:\n raise ValueError('encoding cannot be empty')\n\n exc = None\n if six.PY3:\n if isinstance(s, str):\n return _normalize(s)\n elif isinstance(s, (bytes, bytearray)):\n return _normalize(to_str(s, encoding, errors))\n raise TypeError('expected str, bytes, or bytearray')\n else:\n # This needs to be str and not six.string_types, since if the string is\n # already a unicode type, it does not need to be decoded (and doing so\n # will raise an exception).\n if isinstance(s, unicode): # pylint: disable=incompatible-py3-code,undefined-variable\n return _normalize(s)\n elif isinstance(s, (str, bytearray)):\n for enc in encoding:\n try:\n return _normalize(s.decode(enc, errors))\n except UnicodeDecodeError as err:\n exc = err\n continue\n # The only way we get this far is if a UnicodeDecodeError was\n # raised, otherwise we would have already returned (or raised some\n # other exception).\n raise exc # pylint: disable=raising-bad-type\n raise TypeError('expected str or bytearray')\n" ]
# encoding: utf-8 ''' A collection of hashing and encoding utils. ''' from __future__ import absolute_import, unicode_literals, print_function # Import python libs import base64 import hashlib import hmac import random import os # Import Salt libs from salt.ext import six import salt.utils.files import salt.utils.platform import salt.utils.stringutils from salt.utils.decorators.jinja import jinja_filter @jinja_filter('base64_encode') def base64_b64encode(instr): ''' Encode a string as base64 using the "modern" Python interface. Among other possible differences, the "modern" encoder does not include newline ('\\n') characters in the encoded output. ''' return salt.utils.stringutils.to_unicode( base64.b64encode(salt.utils.stringutils.to_bytes(instr)), encoding='utf8' if salt.utils.platform.is_windows() else None ) @jinja_filter('base64_decode') def base64_b64decode(instr): ''' Decode a base64-encoded string using the "modern" Python interface. ''' decoded = base64.b64decode(salt.utils.stringutils.to_bytes(instr)) try: return salt.utils.stringutils.to_unicode( decoded, encoding='utf8' if salt.utils.platform.is_windows() else None ) except UnicodeDecodeError: return decoded def base64_decodestring(instr): ''' Decode a base64-encoded string using the "legacy" Python interface. ''' b = salt.utils.stringutils.to_bytes(instr) try: # PY3 decoded = base64.decodebytes(b) except AttributeError: # PY2 decoded = base64.decodestring(b) try: return salt.utils.stringutils.to_unicode( decoded, encoding='utf8' if salt.utils.platform.is_windows() else None ) except UnicodeDecodeError: return decoded @jinja_filter('md5') def md5_digest(instr): ''' Generate an md5 hash of a given string. ''' return salt.utils.stringutils.to_unicode( hashlib.md5(salt.utils.stringutils.to_bytes(instr)).hexdigest() ) def sha1_digest(instr): ''' Generate an sha1 hash of a given string. ''' if six.PY3: b = salt.utils.stringutils.to_bytes(instr) return hashlib.sha1(b).hexdigest() return hashlib.sha1(instr).hexdigest() @jinja_filter('sha256') def sha256_digest(instr): ''' Generate a sha256 hash of a given string. ''' return salt.utils.stringutils.to_unicode( hashlib.sha256(salt.utils.stringutils.to_bytes(instr)).hexdigest() ) @jinja_filter('sha512') def sha512_digest(instr): ''' Generate a sha512 hash of a given string ''' return salt.utils.stringutils.to_unicode( hashlib.sha512(salt.utils.stringutils.to_bytes(instr)).hexdigest() ) @jinja_filter('hmac') def hmac_signature(string, shared_secret, challenge_hmac): ''' Verify a challenging hmac signature against a string / shared-secret Returns a boolean if the verification succeeded or failed. ''' msg = salt.utils.stringutils.to_bytes(string) key = salt.utils.stringutils.to_bytes(shared_secret) challenge = salt.utils.stringutils.to_bytes(challenge_hmac) hmac_hash = hmac.new(key, msg, hashlib.sha256) valid_hmac = base64.b64encode(hmac_hash.digest()) return valid_hmac == challenge @jinja_filter('random_hash') def random_hash(size=9999999999, hash_type=None): ''' Return a hash of a randomized data from random.SystemRandom() ''' if not hash_type: hash_type = 'md5' hasher = getattr(hashlib, hash_type) return hasher(salt.utils.stringutils.to_bytes(six.text_type(random.SystemRandom().randint(0, size)))).hexdigest() @jinja_filter('file_hashsum') def get_hash(path, form='sha256', chunk_size=65536): ''' Get the hash sum of a file This is better than ``get_sum`` for the following reasons: - It does not read the entire file into memory. - It does not return a string on error. The returned value of ``get_sum`` cannot really be trusted since it is vulnerable to collisions: ``get_sum(..., 'xyz') == 'Hash xyz not supported'`` ''' hash_type = hasattr(hashlib, form) and getattr(hashlib, form) or None if hash_type is None: raise ValueError('Invalid hash type: {0}'.format(form)) with salt.utils.files.fopen(path, 'rb') as ifile: hash_obj = hash_type() # read the file in in chunks, not the entire file for chunk in iter(lambda: ifile.read(chunk_size), b''): hash_obj.update(chunk) return hash_obj.hexdigest() class DigestCollector(object): ''' Class to collect digest of the file tree. ''' def __init__(self, form='sha256', buff=0x10000): ''' Constructor of the class. :param form: ''' self.__digest = hasattr(hashlib, form) and getattr(hashlib, form)() or None if self.__digest is None: raise ValueError('Invalid hash type: {0}'.format(form)) self.__buff = buff def add(self, path): ''' Update digest with the file content by path. :param path: :return: ''' with salt.utils.files.fopen(path, 'rb') as ifile: for chunk in iter(lambda: ifile.read(self.__buff), b''): self.__digest.update(chunk) def digest(self): ''' Get digest. :return: ''' return salt.utils.stringutils.to_str(self.__digest.hexdigest() + os.linesep)
saltstack/salt
salt/utils/hashutils.py
base64_decodestring
python
def base64_decodestring(instr): ''' Decode a base64-encoded string using the "legacy" Python interface. ''' b = salt.utils.stringutils.to_bytes(instr) try: # PY3 decoded = base64.decodebytes(b) except AttributeError: # PY2 decoded = base64.decodestring(b) try: return salt.utils.stringutils.to_unicode( decoded, encoding='utf8' if salt.utils.platform.is_windows() else None ) except UnicodeDecodeError: return decoded
Decode a base64-encoded string using the "legacy" Python interface.
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/hashutils.py#L66-L83
[ "def to_unicode(s, encoding=None, errors='strict', normalize=False):\n '''\n Given str or unicode, return unicode (str for python 3)\n '''\n def _normalize(s):\n return unicodedata.normalize('NFC', s) if normalize else s\n\n if encoding is None:\n # Try utf-8 first, and fall back to detected encoding\n encoding = ('utf-8', __salt_system_encoding__)\n if not isinstance(encoding, (tuple, list)):\n encoding = (encoding,)\n\n if not encoding:\n raise ValueError('encoding cannot be empty')\n\n exc = None\n if six.PY3:\n if isinstance(s, str):\n return _normalize(s)\n elif isinstance(s, (bytes, bytearray)):\n return _normalize(to_str(s, encoding, errors))\n raise TypeError('expected str, bytes, or bytearray')\n else:\n # This needs to be str and not six.string_types, since if the string is\n # already a unicode type, it does not need to be decoded (and doing so\n # will raise an exception).\n if isinstance(s, unicode): # pylint: disable=incompatible-py3-code,undefined-variable\n return _normalize(s)\n elif isinstance(s, (str, bytearray)):\n for enc in encoding:\n try:\n return _normalize(s.decode(enc, errors))\n except UnicodeDecodeError as err:\n exc = err\n continue\n # The only way we get this far is if a UnicodeDecodeError was\n # raised, otherwise we would have already returned (or raised some\n # other exception).\n raise exc # pylint: disable=raising-bad-type\n raise TypeError('expected str or bytearray')\n" ]
# encoding: utf-8 ''' A collection of hashing and encoding utils. ''' from __future__ import absolute_import, unicode_literals, print_function # Import python libs import base64 import hashlib import hmac import random import os # Import Salt libs from salt.ext import six import salt.utils.files import salt.utils.platform import salt.utils.stringutils from salt.utils.decorators.jinja import jinja_filter @jinja_filter('base64_encode') def base64_b64encode(instr): ''' Encode a string as base64 using the "modern" Python interface. Among other possible differences, the "modern" encoder does not include newline ('\\n') characters in the encoded output. ''' return salt.utils.stringutils.to_unicode( base64.b64encode(salt.utils.stringutils.to_bytes(instr)), encoding='utf8' if salt.utils.platform.is_windows() else None ) @jinja_filter('base64_decode') def base64_b64decode(instr): ''' Decode a base64-encoded string using the "modern" Python interface. ''' decoded = base64.b64decode(salt.utils.stringutils.to_bytes(instr)) try: return salt.utils.stringutils.to_unicode( decoded, encoding='utf8' if salt.utils.platform.is_windows() else None ) except UnicodeDecodeError: return decoded def base64_encodestring(instr): ''' Encode a string as base64 using the "legacy" Python interface. Among other possible differences, the "legacy" encoder includes a newline ('\\n') character after every 76 characters and always at the end of the encoded string. ''' return salt.utils.stringutils.to_unicode( base64.encodestring(salt.utils.stringutils.to_bytes(instr)), encoding='utf8' if salt.utils.platform.is_windows() else None ) @jinja_filter('md5') def md5_digest(instr): ''' Generate an md5 hash of a given string. ''' return salt.utils.stringutils.to_unicode( hashlib.md5(salt.utils.stringutils.to_bytes(instr)).hexdigest() ) def sha1_digest(instr): ''' Generate an sha1 hash of a given string. ''' if six.PY3: b = salt.utils.stringutils.to_bytes(instr) return hashlib.sha1(b).hexdigest() return hashlib.sha1(instr).hexdigest() @jinja_filter('sha256') def sha256_digest(instr): ''' Generate a sha256 hash of a given string. ''' return salt.utils.stringutils.to_unicode( hashlib.sha256(salt.utils.stringutils.to_bytes(instr)).hexdigest() ) @jinja_filter('sha512') def sha512_digest(instr): ''' Generate a sha512 hash of a given string ''' return salt.utils.stringutils.to_unicode( hashlib.sha512(salt.utils.stringutils.to_bytes(instr)).hexdigest() ) @jinja_filter('hmac') def hmac_signature(string, shared_secret, challenge_hmac): ''' Verify a challenging hmac signature against a string / shared-secret Returns a boolean if the verification succeeded or failed. ''' msg = salt.utils.stringutils.to_bytes(string) key = salt.utils.stringutils.to_bytes(shared_secret) challenge = salt.utils.stringutils.to_bytes(challenge_hmac) hmac_hash = hmac.new(key, msg, hashlib.sha256) valid_hmac = base64.b64encode(hmac_hash.digest()) return valid_hmac == challenge @jinja_filter('random_hash') def random_hash(size=9999999999, hash_type=None): ''' Return a hash of a randomized data from random.SystemRandom() ''' if not hash_type: hash_type = 'md5' hasher = getattr(hashlib, hash_type) return hasher(salt.utils.stringutils.to_bytes(six.text_type(random.SystemRandom().randint(0, size)))).hexdigest() @jinja_filter('file_hashsum') def get_hash(path, form='sha256', chunk_size=65536): ''' Get the hash sum of a file This is better than ``get_sum`` for the following reasons: - It does not read the entire file into memory. - It does not return a string on error. The returned value of ``get_sum`` cannot really be trusted since it is vulnerable to collisions: ``get_sum(..., 'xyz') == 'Hash xyz not supported'`` ''' hash_type = hasattr(hashlib, form) and getattr(hashlib, form) or None if hash_type is None: raise ValueError('Invalid hash type: {0}'.format(form)) with salt.utils.files.fopen(path, 'rb') as ifile: hash_obj = hash_type() # read the file in in chunks, not the entire file for chunk in iter(lambda: ifile.read(chunk_size), b''): hash_obj.update(chunk) return hash_obj.hexdigest() class DigestCollector(object): ''' Class to collect digest of the file tree. ''' def __init__(self, form='sha256', buff=0x10000): ''' Constructor of the class. :param form: ''' self.__digest = hasattr(hashlib, form) and getattr(hashlib, form)() or None if self.__digest is None: raise ValueError('Invalid hash type: {0}'.format(form)) self.__buff = buff def add(self, path): ''' Update digest with the file content by path. :param path: :return: ''' with salt.utils.files.fopen(path, 'rb') as ifile: for chunk in iter(lambda: ifile.read(self.__buff), b''): self.__digest.update(chunk) def digest(self): ''' Get digest. :return: ''' return salt.utils.stringutils.to_str(self.__digest.hexdigest() + os.linesep)
saltstack/salt
salt/utils/hashutils.py
md5_digest
python
def md5_digest(instr): ''' Generate an md5 hash of a given string. ''' return salt.utils.stringutils.to_unicode( hashlib.md5(salt.utils.stringutils.to_bytes(instr)).hexdigest() )
Generate an md5 hash of a given string.
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/hashutils.py#L87-L93
[ "def to_unicode(s, encoding=None, errors='strict', normalize=False):\n '''\n Given str or unicode, return unicode (str for python 3)\n '''\n def _normalize(s):\n return unicodedata.normalize('NFC', s) if normalize else s\n\n if encoding is None:\n # Try utf-8 first, and fall back to detected encoding\n encoding = ('utf-8', __salt_system_encoding__)\n if not isinstance(encoding, (tuple, list)):\n encoding = (encoding,)\n\n if not encoding:\n raise ValueError('encoding cannot be empty')\n\n exc = None\n if six.PY3:\n if isinstance(s, str):\n return _normalize(s)\n elif isinstance(s, (bytes, bytearray)):\n return _normalize(to_str(s, encoding, errors))\n raise TypeError('expected str, bytes, or bytearray')\n else:\n # This needs to be str and not six.string_types, since if the string is\n # already a unicode type, it does not need to be decoded (and doing so\n # will raise an exception).\n if isinstance(s, unicode): # pylint: disable=incompatible-py3-code,undefined-variable\n return _normalize(s)\n elif isinstance(s, (str, bytearray)):\n for enc in encoding:\n try:\n return _normalize(s.decode(enc, errors))\n except UnicodeDecodeError as err:\n exc = err\n continue\n # The only way we get this far is if a UnicodeDecodeError was\n # raised, otherwise we would have already returned (or raised some\n # other exception).\n raise exc # pylint: disable=raising-bad-type\n raise TypeError('expected str or bytearray')\n" ]
# encoding: utf-8 ''' A collection of hashing and encoding utils. ''' from __future__ import absolute_import, unicode_literals, print_function # Import python libs import base64 import hashlib import hmac import random import os # Import Salt libs from salt.ext import six import salt.utils.files import salt.utils.platform import salt.utils.stringutils from salt.utils.decorators.jinja import jinja_filter @jinja_filter('base64_encode') def base64_b64encode(instr): ''' Encode a string as base64 using the "modern" Python interface. Among other possible differences, the "modern" encoder does not include newline ('\\n') characters in the encoded output. ''' return salt.utils.stringutils.to_unicode( base64.b64encode(salt.utils.stringutils.to_bytes(instr)), encoding='utf8' if salt.utils.platform.is_windows() else None ) @jinja_filter('base64_decode') def base64_b64decode(instr): ''' Decode a base64-encoded string using the "modern" Python interface. ''' decoded = base64.b64decode(salt.utils.stringutils.to_bytes(instr)) try: return salt.utils.stringutils.to_unicode( decoded, encoding='utf8' if salt.utils.platform.is_windows() else None ) except UnicodeDecodeError: return decoded def base64_encodestring(instr): ''' Encode a string as base64 using the "legacy" Python interface. Among other possible differences, the "legacy" encoder includes a newline ('\\n') character after every 76 characters and always at the end of the encoded string. ''' return salt.utils.stringutils.to_unicode( base64.encodestring(salt.utils.stringutils.to_bytes(instr)), encoding='utf8' if salt.utils.platform.is_windows() else None ) def base64_decodestring(instr): ''' Decode a base64-encoded string using the "legacy" Python interface. ''' b = salt.utils.stringutils.to_bytes(instr) try: # PY3 decoded = base64.decodebytes(b) except AttributeError: # PY2 decoded = base64.decodestring(b) try: return salt.utils.stringutils.to_unicode( decoded, encoding='utf8' if salt.utils.platform.is_windows() else None ) except UnicodeDecodeError: return decoded @jinja_filter('md5') def sha1_digest(instr): ''' Generate an sha1 hash of a given string. ''' if six.PY3: b = salt.utils.stringutils.to_bytes(instr) return hashlib.sha1(b).hexdigest() return hashlib.sha1(instr).hexdigest() @jinja_filter('sha256') def sha256_digest(instr): ''' Generate a sha256 hash of a given string. ''' return salt.utils.stringutils.to_unicode( hashlib.sha256(salt.utils.stringutils.to_bytes(instr)).hexdigest() ) @jinja_filter('sha512') def sha512_digest(instr): ''' Generate a sha512 hash of a given string ''' return salt.utils.stringutils.to_unicode( hashlib.sha512(salt.utils.stringutils.to_bytes(instr)).hexdigest() ) @jinja_filter('hmac') def hmac_signature(string, shared_secret, challenge_hmac): ''' Verify a challenging hmac signature against a string / shared-secret Returns a boolean if the verification succeeded or failed. ''' msg = salt.utils.stringutils.to_bytes(string) key = salt.utils.stringutils.to_bytes(shared_secret) challenge = salt.utils.stringutils.to_bytes(challenge_hmac) hmac_hash = hmac.new(key, msg, hashlib.sha256) valid_hmac = base64.b64encode(hmac_hash.digest()) return valid_hmac == challenge @jinja_filter('random_hash') def random_hash(size=9999999999, hash_type=None): ''' Return a hash of a randomized data from random.SystemRandom() ''' if not hash_type: hash_type = 'md5' hasher = getattr(hashlib, hash_type) return hasher(salt.utils.stringutils.to_bytes(six.text_type(random.SystemRandom().randint(0, size)))).hexdigest() @jinja_filter('file_hashsum') def get_hash(path, form='sha256', chunk_size=65536): ''' Get the hash sum of a file This is better than ``get_sum`` for the following reasons: - It does not read the entire file into memory. - It does not return a string on error. The returned value of ``get_sum`` cannot really be trusted since it is vulnerable to collisions: ``get_sum(..., 'xyz') == 'Hash xyz not supported'`` ''' hash_type = hasattr(hashlib, form) and getattr(hashlib, form) or None if hash_type is None: raise ValueError('Invalid hash type: {0}'.format(form)) with salt.utils.files.fopen(path, 'rb') as ifile: hash_obj = hash_type() # read the file in in chunks, not the entire file for chunk in iter(lambda: ifile.read(chunk_size), b''): hash_obj.update(chunk) return hash_obj.hexdigest() class DigestCollector(object): ''' Class to collect digest of the file tree. ''' def __init__(self, form='sha256', buff=0x10000): ''' Constructor of the class. :param form: ''' self.__digest = hasattr(hashlib, form) and getattr(hashlib, form)() or None if self.__digest is None: raise ValueError('Invalid hash type: {0}'.format(form)) self.__buff = buff def add(self, path): ''' Update digest with the file content by path. :param path: :return: ''' with salt.utils.files.fopen(path, 'rb') as ifile: for chunk in iter(lambda: ifile.read(self.__buff), b''): self.__digest.update(chunk) def digest(self): ''' Get digest. :return: ''' return salt.utils.stringutils.to_str(self.__digest.hexdigest() + os.linesep)
saltstack/salt
salt/utils/hashutils.py
sha1_digest
python
def sha1_digest(instr): ''' Generate an sha1 hash of a given string. ''' if six.PY3: b = salt.utils.stringutils.to_bytes(instr) return hashlib.sha1(b).hexdigest() return hashlib.sha1(instr).hexdigest()
Generate an sha1 hash of a given string.
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/hashutils.py#L96-L103
null
# encoding: utf-8 ''' A collection of hashing and encoding utils. ''' from __future__ import absolute_import, unicode_literals, print_function # Import python libs import base64 import hashlib import hmac import random import os # Import Salt libs from salt.ext import six import salt.utils.files import salt.utils.platform import salt.utils.stringutils from salt.utils.decorators.jinja import jinja_filter @jinja_filter('base64_encode') def base64_b64encode(instr): ''' Encode a string as base64 using the "modern" Python interface. Among other possible differences, the "modern" encoder does not include newline ('\\n') characters in the encoded output. ''' return salt.utils.stringutils.to_unicode( base64.b64encode(salt.utils.stringutils.to_bytes(instr)), encoding='utf8' if salt.utils.platform.is_windows() else None ) @jinja_filter('base64_decode') def base64_b64decode(instr): ''' Decode a base64-encoded string using the "modern" Python interface. ''' decoded = base64.b64decode(salt.utils.stringutils.to_bytes(instr)) try: return salt.utils.stringutils.to_unicode( decoded, encoding='utf8' if salt.utils.platform.is_windows() else None ) except UnicodeDecodeError: return decoded def base64_encodestring(instr): ''' Encode a string as base64 using the "legacy" Python interface. Among other possible differences, the "legacy" encoder includes a newline ('\\n') character after every 76 characters and always at the end of the encoded string. ''' return salt.utils.stringutils.to_unicode( base64.encodestring(salt.utils.stringutils.to_bytes(instr)), encoding='utf8' if salt.utils.platform.is_windows() else None ) def base64_decodestring(instr): ''' Decode a base64-encoded string using the "legacy" Python interface. ''' b = salt.utils.stringutils.to_bytes(instr) try: # PY3 decoded = base64.decodebytes(b) except AttributeError: # PY2 decoded = base64.decodestring(b) try: return salt.utils.stringutils.to_unicode( decoded, encoding='utf8' if salt.utils.platform.is_windows() else None ) except UnicodeDecodeError: return decoded @jinja_filter('md5') def md5_digest(instr): ''' Generate an md5 hash of a given string. ''' return salt.utils.stringutils.to_unicode( hashlib.md5(salt.utils.stringutils.to_bytes(instr)).hexdigest() ) @jinja_filter('sha256') def sha256_digest(instr): ''' Generate a sha256 hash of a given string. ''' return salt.utils.stringutils.to_unicode( hashlib.sha256(salt.utils.stringutils.to_bytes(instr)).hexdigest() ) @jinja_filter('sha512') def sha512_digest(instr): ''' Generate a sha512 hash of a given string ''' return salt.utils.stringutils.to_unicode( hashlib.sha512(salt.utils.stringutils.to_bytes(instr)).hexdigest() ) @jinja_filter('hmac') def hmac_signature(string, shared_secret, challenge_hmac): ''' Verify a challenging hmac signature against a string / shared-secret Returns a boolean if the verification succeeded or failed. ''' msg = salt.utils.stringutils.to_bytes(string) key = salt.utils.stringutils.to_bytes(shared_secret) challenge = salt.utils.stringutils.to_bytes(challenge_hmac) hmac_hash = hmac.new(key, msg, hashlib.sha256) valid_hmac = base64.b64encode(hmac_hash.digest()) return valid_hmac == challenge @jinja_filter('random_hash') def random_hash(size=9999999999, hash_type=None): ''' Return a hash of a randomized data from random.SystemRandom() ''' if not hash_type: hash_type = 'md5' hasher = getattr(hashlib, hash_type) return hasher(salt.utils.stringutils.to_bytes(six.text_type(random.SystemRandom().randint(0, size)))).hexdigest() @jinja_filter('file_hashsum') def get_hash(path, form='sha256', chunk_size=65536): ''' Get the hash sum of a file This is better than ``get_sum`` for the following reasons: - It does not read the entire file into memory. - It does not return a string on error. The returned value of ``get_sum`` cannot really be trusted since it is vulnerable to collisions: ``get_sum(..., 'xyz') == 'Hash xyz not supported'`` ''' hash_type = hasattr(hashlib, form) and getattr(hashlib, form) or None if hash_type is None: raise ValueError('Invalid hash type: {0}'.format(form)) with salt.utils.files.fopen(path, 'rb') as ifile: hash_obj = hash_type() # read the file in in chunks, not the entire file for chunk in iter(lambda: ifile.read(chunk_size), b''): hash_obj.update(chunk) return hash_obj.hexdigest() class DigestCollector(object): ''' Class to collect digest of the file tree. ''' def __init__(self, form='sha256', buff=0x10000): ''' Constructor of the class. :param form: ''' self.__digest = hasattr(hashlib, form) and getattr(hashlib, form)() or None if self.__digest is None: raise ValueError('Invalid hash type: {0}'.format(form)) self.__buff = buff def add(self, path): ''' Update digest with the file content by path. :param path: :return: ''' with salt.utils.files.fopen(path, 'rb') as ifile: for chunk in iter(lambda: ifile.read(self.__buff), b''): self.__digest.update(chunk) def digest(self): ''' Get digest. :return: ''' return salt.utils.stringutils.to_str(self.__digest.hexdigest() + os.linesep)
saltstack/salt
salt/utils/hashutils.py
sha256_digest
python
def sha256_digest(instr): ''' Generate a sha256 hash of a given string. ''' return salt.utils.stringutils.to_unicode( hashlib.sha256(salt.utils.stringutils.to_bytes(instr)).hexdigest() )
Generate a sha256 hash of a given string.
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/hashutils.py#L107-L113
[ "def to_unicode(s, encoding=None, errors='strict', normalize=False):\n '''\n Given str or unicode, return unicode (str for python 3)\n '''\n def _normalize(s):\n return unicodedata.normalize('NFC', s) if normalize else s\n\n if encoding is None:\n # Try utf-8 first, and fall back to detected encoding\n encoding = ('utf-8', __salt_system_encoding__)\n if not isinstance(encoding, (tuple, list)):\n encoding = (encoding,)\n\n if not encoding:\n raise ValueError('encoding cannot be empty')\n\n exc = None\n if six.PY3:\n if isinstance(s, str):\n return _normalize(s)\n elif isinstance(s, (bytes, bytearray)):\n return _normalize(to_str(s, encoding, errors))\n raise TypeError('expected str, bytes, or bytearray')\n else:\n # This needs to be str and not six.string_types, since if the string is\n # already a unicode type, it does not need to be decoded (and doing so\n # will raise an exception).\n if isinstance(s, unicode): # pylint: disable=incompatible-py3-code,undefined-variable\n return _normalize(s)\n elif isinstance(s, (str, bytearray)):\n for enc in encoding:\n try:\n return _normalize(s.decode(enc, errors))\n except UnicodeDecodeError as err:\n exc = err\n continue\n # The only way we get this far is if a UnicodeDecodeError was\n # raised, otherwise we would have already returned (or raised some\n # other exception).\n raise exc # pylint: disable=raising-bad-type\n raise TypeError('expected str or bytearray')\n" ]
# encoding: utf-8 ''' A collection of hashing and encoding utils. ''' from __future__ import absolute_import, unicode_literals, print_function # Import python libs import base64 import hashlib import hmac import random import os # Import Salt libs from salt.ext import six import salt.utils.files import salt.utils.platform import salt.utils.stringutils from salt.utils.decorators.jinja import jinja_filter @jinja_filter('base64_encode') def base64_b64encode(instr): ''' Encode a string as base64 using the "modern" Python interface. Among other possible differences, the "modern" encoder does not include newline ('\\n') characters in the encoded output. ''' return salt.utils.stringutils.to_unicode( base64.b64encode(salt.utils.stringutils.to_bytes(instr)), encoding='utf8' if salt.utils.platform.is_windows() else None ) @jinja_filter('base64_decode') def base64_b64decode(instr): ''' Decode a base64-encoded string using the "modern" Python interface. ''' decoded = base64.b64decode(salt.utils.stringutils.to_bytes(instr)) try: return salt.utils.stringutils.to_unicode( decoded, encoding='utf8' if salt.utils.platform.is_windows() else None ) except UnicodeDecodeError: return decoded def base64_encodestring(instr): ''' Encode a string as base64 using the "legacy" Python interface. Among other possible differences, the "legacy" encoder includes a newline ('\\n') character after every 76 characters and always at the end of the encoded string. ''' return salt.utils.stringutils.to_unicode( base64.encodestring(salt.utils.stringutils.to_bytes(instr)), encoding='utf8' if salt.utils.platform.is_windows() else None ) def base64_decodestring(instr): ''' Decode a base64-encoded string using the "legacy" Python interface. ''' b = salt.utils.stringutils.to_bytes(instr) try: # PY3 decoded = base64.decodebytes(b) except AttributeError: # PY2 decoded = base64.decodestring(b) try: return salt.utils.stringutils.to_unicode( decoded, encoding='utf8' if salt.utils.platform.is_windows() else None ) except UnicodeDecodeError: return decoded @jinja_filter('md5') def md5_digest(instr): ''' Generate an md5 hash of a given string. ''' return salt.utils.stringutils.to_unicode( hashlib.md5(salt.utils.stringutils.to_bytes(instr)).hexdigest() ) def sha1_digest(instr): ''' Generate an sha1 hash of a given string. ''' if six.PY3: b = salt.utils.stringutils.to_bytes(instr) return hashlib.sha1(b).hexdigest() return hashlib.sha1(instr).hexdigest() @jinja_filter('sha256') @jinja_filter('sha512') def sha512_digest(instr): ''' Generate a sha512 hash of a given string ''' return salt.utils.stringutils.to_unicode( hashlib.sha512(salt.utils.stringutils.to_bytes(instr)).hexdigest() ) @jinja_filter('hmac') def hmac_signature(string, shared_secret, challenge_hmac): ''' Verify a challenging hmac signature against a string / shared-secret Returns a boolean if the verification succeeded or failed. ''' msg = salt.utils.stringutils.to_bytes(string) key = salt.utils.stringutils.to_bytes(shared_secret) challenge = salt.utils.stringutils.to_bytes(challenge_hmac) hmac_hash = hmac.new(key, msg, hashlib.sha256) valid_hmac = base64.b64encode(hmac_hash.digest()) return valid_hmac == challenge @jinja_filter('random_hash') def random_hash(size=9999999999, hash_type=None): ''' Return a hash of a randomized data from random.SystemRandom() ''' if not hash_type: hash_type = 'md5' hasher = getattr(hashlib, hash_type) return hasher(salt.utils.stringutils.to_bytes(six.text_type(random.SystemRandom().randint(0, size)))).hexdigest() @jinja_filter('file_hashsum') def get_hash(path, form='sha256', chunk_size=65536): ''' Get the hash sum of a file This is better than ``get_sum`` for the following reasons: - It does not read the entire file into memory. - It does not return a string on error. The returned value of ``get_sum`` cannot really be trusted since it is vulnerable to collisions: ``get_sum(..., 'xyz') == 'Hash xyz not supported'`` ''' hash_type = hasattr(hashlib, form) and getattr(hashlib, form) or None if hash_type is None: raise ValueError('Invalid hash type: {0}'.format(form)) with salt.utils.files.fopen(path, 'rb') as ifile: hash_obj = hash_type() # read the file in in chunks, not the entire file for chunk in iter(lambda: ifile.read(chunk_size), b''): hash_obj.update(chunk) return hash_obj.hexdigest() class DigestCollector(object): ''' Class to collect digest of the file tree. ''' def __init__(self, form='sha256', buff=0x10000): ''' Constructor of the class. :param form: ''' self.__digest = hasattr(hashlib, form) and getattr(hashlib, form)() or None if self.__digest is None: raise ValueError('Invalid hash type: {0}'.format(form)) self.__buff = buff def add(self, path): ''' Update digest with the file content by path. :param path: :return: ''' with salt.utils.files.fopen(path, 'rb') as ifile: for chunk in iter(lambda: ifile.read(self.__buff), b''): self.__digest.update(chunk) def digest(self): ''' Get digest. :return: ''' return salt.utils.stringutils.to_str(self.__digest.hexdigest() + os.linesep)
saltstack/salt
salt/utils/hashutils.py
sha512_digest
python
def sha512_digest(instr): ''' Generate a sha512 hash of a given string ''' return salt.utils.stringutils.to_unicode( hashlib.sha512(salt.utils.stringutils.to_bytes(instr)).hexdigest() )
Generate a sha512 hash of a given string
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/hashutils.py#L117-L123
[ "def to_unicode(s, encoding=None, errors='strict', normalize=False):\n '''\n Given str or unicode, return unicode (str for python 3)\n '''\n def _normalize(s):\n return unicodedata.normalize('NFC', s) if normalize else s\n\n if encoding is None:\n # Try utf-8 first, and fall back to detected encoding\n encoding = ('utf-8', __salt_system_encoding__)\n if not isinstance(encoding, (tuple, list)):\n encoding = (encoding,)\n\n if not encoding:\n raise ValueError('encoding cannot be empty')\n\n exc = None\n if six.PY3:\n if isinstance(s, str):\n return _normalize(s)\n elif isinstance(s, (bytes, bytearray)):\n return _normalize(to_str(s, encoding, errors))\n raise TypeError('expected str, bytes, or bytearray')\n else:\n # This needs to be str and not six.string_types, since if the string is\n # already a unicode type, it does not need to be decoded (and doing so\n # will raise an exception).\n if isinstance(s, unicode): # pylint: disable=incompatible-py3-code,undefined-variable\n return _normalize(s)\n elif isinstance(s, (str, bytearray)):\n for enc in encoding:\n try:\n return _normalize(s.decode(enc, errors))\n except UnicodeDecodeError as err:\n exc = err\n continue\n # The only way we get this far is if a UnicodeDecodeError was\n # raised, otherwise we would have already returned (or raised some\n # other exception).\n raise exc # pylint: disable=raising-bad-type\n raise TypeError('expected str or bytearray')\n" ]
# encoding: utf-8 ''' A collection of hashing and encoding utils. ''' from __future__ import absolute_import, unicode_literals, print_function # Import python libs import base64 import hashlib import hmac import random import os # Import Salt libs from salt.ext import six import salt.utils.files import salt.utils.platform import salt.utils.stringutils from salt.utils.decorators.jinja import jinja_filter @jinja_filter('base64_encode') def base64_b64encode(instr): ''' Encode a string as base64 using the "modern" Python interface. Among other possible differences, the "modern" encoder does not include newline ('\\n') characters in the encoded output. ''' return salt.utils.stringutils.to_unicode( base64.b64encode(salt.utils.stringutils.to_bytes(instr)), encoding='utf8' if salt.utils.platform.is_windows() else None ) @jinja_filter('base64_decode') def base64_b64decode(instr): ''' Decode a base64-encoded string using the "modern" Python interface. ''' decoded = base64.b64decode(salt.utils.stringutils.to_bytes(instr)) try: return salt.utils.stringutils.to_unicode( decoded, encoding='utf8' if salt.utils.platform.is_windows() else None ) except UnicodeDecodeError: return decoded def base64_encodestring(instr): ''' Encode a string as base64 using the "legacy" Python interface. Among other possible differences, the "legacy" encoder includes a newline ('\\n') character after every 76 characters and always at the end of the encoded string. ''' return salt.utils.stringutils.to_unicode( base64.encodestring(salt.utils.stringutils.to_bytes(instr)), encoding='utf8' if salt.utils.platform.is_windows() else None ) def base64_decodestring(instr): ''' Decode a base64-encoded string using the "legacy" Python interface. ''' b = salt.utils.stringutils.to_bytes(instr) try: # PY3 decoded = base64.decodebytes(b) except AttributeError: # PY2 decoded = base64.decodestring(b) try: return salt.utils.stringutils.to_unicode( decoded, encoding='utf8' if salt.utils.platform.is_windows() else None ) except UnicodeDecodeError: return decoded @jinja_filter('md5') def md5_digest(instr): ''' Generate an md5 hash of a given string. ''' return salt.utils.stringutils.to_unicode( hashlib.md5(salt.utils.stringutils.to_bytes(instr)).hexdigest() ) def sha1_digest(instr): ''' Generate an sha1 hash of a given string. ''' if six.PY3: b = salt.utils.stringutils.to_bytes(instr) return hashlib.sha1(b).hexdigest() return hashlib.sha1(instr).hexdigest() @jinja_filter('sha256') def sha256_digest(instr): ''' Generate a sha256 hash of a given string. ''' return salt.utils.stringutils.to_unicode( hashlib.sha256(salt.utils.stringutils.to_bytes(instr)).hexdigest() ) @jinja_filter('sha512') @jinja_filter('hmac') def hmac_signature(string, shared_secret, challenge_hmac): ''' Verify a challenging hmac signature against a string / shared-secret Returns a boolean if the verification succeeded or failed. ''' msg = salt.utils.stringutils.to_bytes(string) key = salt.utils.stringutils.to_bytes(shared_secret) challenge = salt.utils.stringutils.to_bytes(challenge_hmac) hmac_hash = hmac.new(key, msg, hashlib.sha256) valid_hmac = base64.b64encode(hmac_hash.digest()) return valid_hmac == challenge @jinja_filter('random_hash') def random_hash(size=9999999999, hash_type=None): ''' Return a hash of a randomized data from random.SystemRandom() ''' if not hash_type: hash_type = 'md5' hasher = getattr(hashlib, hash_type) return hasher(salt.utils.stringutils.to_bytes(six.text_type(random.SystemRandom().randint(0, size)))).hexdigest() @jinja_filter('file_hashsum') def get_hash(path, form='sha256', chunk_size=65536): ''' Get the hash sum of a file This is better than ``get_sum`` for the following reasons: - It does not read the entire file into memory. - It does not return a string on error. The returned value of ``get_sum`` cannot really be trusted since it is vulnerable to collisions: ``get_sum(..., 'xyz') == 'Hash xyz not supported'`` ''' hash_type = hasattr(hashlib, form) and getattr(hashlib, form) or None if hash_type is None: raise ValueError('Invalid hash type: {0}'.format(form)) with salt.utils.files.fopen(path, 'rb') as ifile: hash_obj = hash_type() # read the file in in chunks, not the entire file for chunk in iter(lambda: ifile.read(chunk_size), b''): hash_obj.update(chunk) return hash_obj.hexdigest() class DigestCollector(object): ''' Class to collect digest of the file tree. ''' def __init__(self, form='sha256', buff=0x10000): ''' Constructor of the class. :param form: ''' self.__digest = hasattr(hashlib, form) and getattr(hashlib, form)() or None if self.__digest is None: raise ValueError('Invalid hash type: {0}'.format(form)) self.__buff = buff def add(self, path): ''' Update digest with the file content by path. :param path: :return: ''' with salt.utils.files.fopen(path, 'rb') as ifile: for chunk in iter(lambda: ifile.read(self.__buff), b''): self.__digest.update(chunk) def digest(self): ''' Get digest. :return: ''' return salt.utils.stringutils.to_str(self.__digest.hexdigest() + os.linesep)
saltstack/salt
salt/utils/hashutils.py
hmac_signature
python
def hmac_signature(string, shared_secret, challenge_hmac): ''' Verify a challenging hmac signature against a string / shared-secret Returns a boolean if the verification succeeded or failed. ''' msg = salt.utils.stringutils.to_bytes(string) key = salt.utils.stringutils.to_bytes(shared_secret) challenge = salt.utils.stringutils.to_bytes(challenge_hmac) hmac_hash = hmac.new(key, msg, hashlib.sha256) valid_hmac = base64.b64encode(hmac_hash.digest()) return valid_hmac == challenge
Verify a challenging hmac signature against a string / shared-secret Returns a boolean if the verification succeeded or failed.
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/hashutils.py#L127-L137
null
# encoding: utf-8 ''' A collection of hashing and encoding utils. ''' from __future__ import absolute_import, unicode_literals, print_function # Import python libs import base64 import hashlib import hmac import random import os # Import Salt libs from salt.ext import six import salt.utils.files import salt.utils.platform import salt.utils.stringutils from salt.utils.decorators.jinja import jinja_filter @jinja_filter('base64_encode') def base64_b64encode(instr): ''' Encode a string as base64 using the "modern" Python interface. Among other possible differences, the "modern" encoder does not include newline ('\\n') characters in the encoded output. ''' return salt.utils.stringutils.to_unicode( base64.b64encode(salt.utils.stringutils.to_bytes(instr)), encoding='utf8' if salt.utils.platform.is_windows() else None ) @jinja_filter('base64_decode') def base64_b64decode(instr): ''' Decode a base64-encoded string using the "modern" Python interface. ''' decoded = base64.b64decode(salt.utils.stringutils.to_bytes(instr)) try: return salt.utils.stringutils.to_unicode( decoded, encoding='utf8' if salt.utils.platform.is_windows() else None ) except UnicodeDecodeError: return decoded def base64_encodestring(instr): ''' Encode a string as base64 using the "legacy" Python interface. Among other possible differences, the "legacy" encoder includes a newline ('\\n') character after every 76 characters and always at the end of the encoded string. ''' return salt.utils.stringutils.to_unicode( base64.encodestring(salt.utils.stringutils.to_bytes(instr)), encoding='utf8' if salt.utils.platform.is_windows() else None ) def base64_decodestring(instr): ''' Decode a base64-encoded string using the "legacy" Python interface. ''' b = salt.utils.stringutils.to_bytes(instr) try: # PY3 decoded = base64.decodebytes(b) except AttributeError: # PY2 decoded = base64.decodestring(b) try: return salt.utils.stringutils.to_unicode( decoded, encoding='utf8' if salt.utils.platform.is_windows() else None ) except UnicodeDecodeError: return decoded @jinja_filter('md5') def md5_digest(instr): ''' Generate an md5 hash of a given string. ''' return salt.utils.stringutils.to_unicode( hashlib.md5(salt.utils.stringutils.to_bytes(instr)).hexdigest() ) def sha1_digest(instr): ''' Generate an sha1 hash of a given string. ''' if six.PY3: b = salt.utils.stringutils.to_bytes(instr) return hashlib.sha1(b).hexdigest() return hashlib.sha1(instr).hexdigest() @jinja_filter('sha256') def sha256_digest(instr): ''' Generate a sha256 hash of a given string. ''' return salt.utils.stringutils.to_unicode( hashlib.sha256(salt.utils.stringutils.to_bytes(instr)).hexdigest() ) @jinja_filter('sha512') def sha512_digest(instr): ''' Generate a sha512 hash of a given string ''' return salt.utils.stringutils.to_unicode( hashlib.sha512(salt.utils.stringutils.to_bytes(instr)).hexdigest() ) @jinja_filter('hmac') @jinja_filter('random_hash') def random_hash(size=9999999999, hash_type=None): ''' Return a hash of a randomized data from random.SystemRandom() ''' if not hash_type: hash_type = 'md5' hasher = getattr(hashlib, hash_type) return hasher(salt.utils.stringutils.to_bytes(six.text_type(random.SystemRandom().randint(0, size)))).hexdigest() @jinja_filter('file_hashsum') def get_hash(path, form='sha256', chunk_size=65536): ''' Get the hash sum of a file This is better than ``get_sum`` for the following reasons: - It does not read the entire file into memory. - It does not return a string on error. The returned value of ``get_sum`` cannot really be trusted since it is vulnerable to collisions: ``get_sum(..., 'xyz') == 'Hash xyz not supported'`` ''' hash_type = hasattr(hashlib, form) and getattr(hashlib, form) or None if hash_type is None: raise ValueError('Invalid hash type: {0}'.format(form)) with salt.utils.files.fopen(path, 'rb') as ifile: hash_obj = hash_type() # read the file in in chunks, not the entire file for chunk in iter(lambda: ifile.read(chunk_size), b''): hash_obj.update(chunk) return hash_obj.hexdigest() class DigestCollector(object): ''' Class to collect digest of the file tree. ''' def __init__(self, form='sha256', buff=0x10000): ''' Constructor of the class. :param form: ''' self.__digest = hasattr(hashlib, form) and getattr(hashlib, form)() or None if self.__digest is None: raise ValueError('Invalid hash type: {0}'.format(form)) self.__buff = buff def add(self, path): ''' Update digest with the file content by path. :param path: :return: ''' with salt.utils.files.fopen(path, 'rb') as ifile: for chunk in iter(lambda: ifile.read(self.__buff), b''): self.__digest.update(chunk) def digest(self): ''' Get digest. :return: ''' return salt.utils.stringutils.to_str(self.__digest.hexdigest() + os.linesep)
saltstack/salt
salt/utils/hashutils.py
random_hash
python
def random_hash(size=9999999999, hash_type=None): ''' Return a hash of a randomized data from random.SystemRandom() ''' if not hash_type: hash_type = 'md5' hasher = getattr(hashlib, hash_type) return hasher(salt.utils.stringutils.to_bytes(six.text_type(random.SystemRandom().randint(0, size)))).hexdigest()
Return a hash of a randomized data from random.SystemRandom()
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/hashutils.py#L141-L148
null
# encoding: utf-8 ''' A collection of hashing and encoding utils. ''' from __future__ import absolute_import, unicode_literals, print_function # Import python libs import base64 import hashlib import hmac import random import os # Import Salt libs from salt.ext import six import salt.utils.files import salt.utils.platform import salt.utils.stringutils from salt.utils.decorators.jinja import jinja_filter @jinja_filter('base64_encode') def base64_b64encode(instr): ''' Encode a string as base64 using the "modern" Python interface. Among other possible differences, the "modern" encoder does not include newline ('\\n') characters in the encoded output. ''' return salt.utils.stringutils.to_unicode( base64.b64encode(salt.utils.stringutils.to_bytes(instr)), encoding='utf8' if salt.utils.platform.is_windows() else None ) @jinja_filter('base64_decode') def base64_b64decode(instr): ''' Decode a base64-encoded string using the "modern" Python interface. ''' decoded = base64.b64decode(salt.utils.stringutils.to_bytes(instr)) try: return salt.utils.stringutils.to_unicode( decoded, encoding='utf8' if salt.utils.platform.is_windows() else None ) except UnicodeDecodeError: return decoded def base64_encodestring(instr): ''' Encode a string as base64 using the "legacy" Python interface. Among other possible differences, the "legacy" encoder includes a newline ('\\n') character after every 76 characters and always at the end of the encoded string. ''' return salt.utils.stringutils.to_unicode( base64.encodestring(salt.utils.stringutils.to_bytes(instr)), encoding='utf8' if salt.utils.platform.is_windows() else None ) def base64_decodestring(instr): ''' Decode a base64-encoded string using the "legacy" Python interface. ''' b = salt.utils.stringutils.to_bytes(instr) try: # PY3 decoded = base64.decodebytes(b) except AttributeError: # PY2 decoded = base64.decodestring(b) try: return salt.utils.stringutils.to_unicode( decoded, encoding='utf8' if salt.utils.platform.is_windows() else None ) except UnicodeDecodeError: return decoded @jinja_filter('md5') def md5_digest(instr): ''' Generate an md5 hash of a given string. ''' return salt.utils.stringutils.to_unicode( hashlib.md5(salt.utils.stringutils.to_bytes(instr)).hexdigest() ) def sha1_digest(instr): ''' Generate an sha1 hash of a given string. ''' if six.PY3: b = salt.utils.stringutils.to_bytes(instr) return hashlib.sha1(b).hexdigest() return hashlib.sha1(instr).hexdigest() @jinja_filter('sha256') def sha256_digest(instr): ''' Generate a sha256 hash of a given string. ''' return salt.utils.stringutils.to_unicode( hashlib.sha256(salt.utils.stringutils.to_bytes(instr)).hexdigest() ) @jinja_filter('sha512') def sha512_digest(instr): ''' Generate a sha512 hash of a given string ''' return salt.utils.stringutils.to_unicode( hashlib.sha512(salt.utils.stringutils.to_bytes(instr)).hexdigest() ) @jinja_filter('hmac') def hmac_signature(string, shared_secret, challenge_hmac): ''' Verify a challenging hmac signature against a string / shared-secret Returns a boolean if the verification succeeded or failed. ''' msg = salt.utils.stringutils.to_bytes(string) key = salt.utils.stringutils.to_bytes(shared_secret) challenge = salt.utils.stringutils.to_bytes(challenge_hmac) hmac_hash = hmac.new(key, msg, hashlib.sha256) valid_hmac = base64.b64encode(hmac_hash.digest()) return valid_hmac == challenge @jinja_filter('random_hash') @jinja_filter('file_hashsum') def get_hash(path, form='sha256', chunk_size=65536): ''' Get the hash sum of a file This is better than ``get_sum`` for the following reasons: - It does not read the entire file into memory. - It does not return a string on error. The returned value of ``get_sum`` cannot really be trusted since it is vulnerable to collisions: ``get_sum(..., 'xyz') == 'Hash xyz not supported'`` ''' hash_type = hasattr(hashlib, form) and getattr(hashlib, form) or None if hash_type is None: raise ValueError('Invalid hash type: {0}'.format(form)) with salt.utils.files.fopen(path, 'rb') as ifile: hash_obj = hash_type() # read the file in in chunks, not the entire file for chunk in iter(lambda: ifile.read(chunk_size), b''): hash_obj.update(chunk) return hash_obj.hexdigest() class DigestCollector(object): ''' Class to collect digest of the file tree. ''' def __init__(self, form='sha256', buff=0x10000): ''' Constructor of the class. :param form: ''' self.__digest = hasattr(hashlib, form) and getattr(hashlib, form)() or None if self.__digest is None: raise ValueError('Invalid hash type: {0}'.format(form)) self.__buff = buff def add(self, path): ''' Update digest with the file content by path. :param path: :return: ''' with salt.utils.files.fopen(path, 'rb') as ifile: for chunk in iter(lambda: ifile.read(self.__buff), b''): self.__digest.update(chunk) def digest(self): ''' Get digest. :return: ''' return salt.utils.stringutils.to_str(self.__digest.hexdigest() + os.linesep)
saltstack/salt
salt/utils/hashutils.py
get_hash
python
def get_hash(path, form='sha256', chunk_size=65536): ''' Get the hash sum of a file This is better than ``get_sum`` for the following reasons: - It does not read the entire file into memory. - It does not return a string on error. The returned value of ``get_sum`` cannot really be trusted since it is vulnerable to collisions: ``get_sum(..., 'xyz') == 'Hash xyz not supported'`` ''' hash_type = hasattr(hashlib, form) and getattr(hashlib, form) or None if hash_type is None: raise ValueError('Invalid hash type: {0}'.format(form)) with salt.utils.files.fopen(path, 'rb') as ifile: hash_obj = hash_type() # read the file in in chunks, not the entire file for chunk in iter(lambda: ifile.read(chunk_size), b''): hash_obj.update(chunk) return hash_obj.hexdigest()
Get the hash sum of a file This is better than ``get_sum`` for the following reasons: - It does not read the entire file into memory. - It does not return a string on error. The returned value of ``get_sum`` cannot really be trusted since it is vulnerable to collisions: ``get_sum(..., 'xyz') == 'Hash xyz not supported'``
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/hashutils.py#L152-L171
null
# encoding: utf-8 ''' A collection of hashing and encoding utils. ''' from __future__ import absolute_import, unicode_literals, print_function # Import python libs import base64 import hashlib import hmac import random import os # Import Salt libs from salt.ext import six import salt.utils.files import salt.utils.platform import salt.utils.stringutils from salt.utils.decorators.jinja import jinja_filter @jinja_filter('base64_encode') def base64_b64encode(instr): ''' Encode a string as base64 using the "modern" Python interface. Among other possible differences, the "modern" encoder does not include newline ('\\n') characters in the encoded output. ''' return salt.utils.stringutils.to_unicode( base64.b64encode(salt.utils.stringutils.to_bytes(instr)), encoding='utf8' if salt.utils.platform.is_windows() else None ) @jinja_filter('base64_decode') def base64_b64decode(instr): ''' Decode a base64-encoded string using the "modern" Python interface. ''' decoded = base64.b64decode(salt.utils.stringutils.to_bytes(instr)) try: return salt.utils.stringutils.to_unicode( decoded, encoding='utf8' if salt.utils.platform.is_windows() else None ) except UnicodeDecodeError: return decoded def base64_encodestring(instr): ''' Encode a string as base64 using the "legacy" Python interface. Among other possible differences, the "legacy" encoder includes a newline ('\\n') character after every 76 characters and always at the end of the encoded string. ''' return salt.utils.stringutils.to_unicode( base64.encodestring(salt.utils.stringutils.to_bytes(instr)), encoding='utf8' if salt.utils.platform.is_windows() else None ) def base64_decodestring(instr): ''' Decode a base64-encoded string using the "legacy" Python interface. ''' b = salt.utils.stringutils.to_bytes(instr) try: # PY3 decoded = base64.decodebytes(b) except AttributeError: # PY2 decoded = base64.decodestring(b) try: return salt.utils.stringutils.to_unicode( decoded, encoding='utf8' if salt.utils.platform.is_windows() else None ) except UnicodeDecodeError: return decoded @jinja_filter('md5') def md5_digest(instr): ''' Generate an md5 hash of a given string. ''' return salt.utils.stringutils.to_unicode( hashlib.md5(salt.utils.stringutils.to_bytes(instr)).hexdigest() ) def sha1_digest(instr): ''' Generate an sha1 hash of a given string. ''' if six.PY3: b = salt.utils.stringutils.to_bytes(instr) return hashlib.sha1(b).hexdigest() return hashlib.sha1(instr).hexdigest() @jinja_filter('sha256') def sha256_digest(instr): ''' Generate a sha256 hash of a given string. ''' return salt.utils.stringutils.to_unicode( hashlib.sha256(salt.utils.stringutils.to_bytes(instr)).hexdigest() ) @jinja_filter('sha512') def sha512_digest(instr): ''' Generate a sha512 hash of a given string ''' return salt.utils.stringutils.to_unicode( hashlib.sha512(salt.utils.stringutils.to_bytes(instr)).hexdigest() ) @jinja_filter('hmac') def hmac_signature(string, shared_secret, challenge_hmac): ''' Verify a challenging hmac signature against a string / shared-secret Returns a boolean if the verification succeeded or failed. ''' msg = salt.utils.stringutils.to_bytes(string) key = salt.utils.stringutils.to_bytes(shared_secret) challenge = salt.utils.stringutils.to_bytes(challenge_hmac) hmac_hash = hmac.new(key, msg, hashlib.sha256) valid_hmac = base64.b64encode(hmac_hash.digest()) return valid_hmac == challenge @jinja_filter('random_hash') def random_hash(size=9999999999, hash_type=None): ''' Return a hash of a randomized data from random.SystemRandom() ''' if not hash_type: hash_type = 'md5' hasher = getattr(hashlib, hash_type) return hasher(salt.utils.stringutils.to_bytes(six.text_type(random.SystemRandom().randint(0, size)))).hexdigest() @jinja_filter('file_hashsum') class DigestCollector(object): ''' Class to collect digest of the file tree. ''' def __init__(self, form='sha256', buff=0x10000): ''' Constructor of the class. :param form: ''' self.__digest = hasattr(hashlib, form) and getattr(hashlib, form)() or None if self.__digest is None: raise ValueError('Invalid hash type: {0}'.format(form)) self.__buff = buff def add(self, path): ''' Update digest with the file content by path. :param path: :return: ''' with salt.utils.files.fopen(path, 'rb') as ifile: for chunk in iter(lambda: ifile.read(self.__buff), b''): self.__digest.update(chunk) def digest(self): ''' Get digest. :return: ''' return salt.utils.stringutils.to_str(self.__digest.hexdigest() + os.linesep)
saltstack/salt
salt/utils/hashutils.py
DigestCollector.add
python
def add(self, path): ''' Update digest with the file content by path. :param path: :return: ''' with salt.utils.files.fopen(path, 'rb') as ifile: for chunk in iter(lambda: ifile.read(self.__buff), b''): self.__digest.update(chunk)
Update digest with the file content by path. :param path: :return:
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/hashutils.py#L189-L198
[ "def fopen(*args, **kwargs):\n '''\n Wrapper around open() built-in to set CLOEXEC on the fd.\n\n This flag specifies that the file descriptor should be closed when an exec\n function is invoked;\n\n When a file descriptor is allocated (as with open or dup), this bit is\n initially cleared on the new file descriptor, meaning that descriptor will\n survive into the new program after exec.\n\n NB! We still have small race condition between open and fcntl.\n '''\n if six.PY3:\n try:\n # Don't permit stdin/stdout/stderr to be opened. The boolean False\n # and True are treated by Python 3's open() as file descriptors 0\n # and 1, respectively.\n if args[0] in (0, 1, 2):\n raise TypeError(\n '{0} is not a permitted file descriptor'.format(args[0])\n )\n except IndexError:\n pass\n binary = None\n # ensure 'binary' mode is always used on Windows in Python 2\n if ((six.PY2 and salt.utils.platform.is_windows() and 'binary' not in kwargs) or\n kwargs.pop('binary', False)):\n if len(args) > 1:\n args = list(args)\n if 'b' not in args[1]:\n args[1] = args[1].replace('t', 'b')\n if 'b' not in args[1]:\n args[1] += 'b'\n elif kwargs.get('mode'):\n if 'b' not in kwargs['mode']:\n kwargs['mode'] = kwargs['mode'].replace('t', 'b')\n if 'b' not in kwargs['mode']:\n kwargs['mode'] += 'b'\n else:\n # the default is to read\n kwargs['mode'] = 'rb'\n elif six.PY3 and 'encoding' not in kwargs:\n # In Python 3, if text mode is used and the encoding\n # is not specified, set the encoding to 'utf-8'.\n binary = False\n if len(args) > 1:\n args = list(args)\n if 'b' in args[1]:\n binary = True\n if kwargs.get('mode', None):\n if 'b' in kwargs['mode']:\n binary = True\n if not binary:\n kwargs['encoding'] = __salt_system_encoding__\n\n if six.PY3 and not binary and not kwargs.get('newline', None):\n kwargs['newline'] = ''\n\n f_handle = open(*args, **kwargs) # pylint: disable=resource-leakage\n\n if is_fcntl_available():\n # modify the file descriptor on systems with fcntl\n # unix and unix-like systems only\n try:\n FD_CLOEXEC = fcntl.FD_CLOEXEC # pylint: disable=C0103\n except AttributeError:\n FD_CLOEXEC = 1 # pylint: disable=C0103\n old_flags = fcntl.fcntl(f_handle.fileno(), fcntl.F_GETFD)\n fcntl.fcntl(f_handle.fileno(), fcntl.F_SETFD, old_flags | FD_CLOEXEC)\n\n return f_handle\n" ]
class DigestCollector(object): ''' Class to collect digest of the file tree. ''' def __init__(self, form='sha256', buff=0x10000): ''' Constructor of the class. :param form: ''' self.__digest = hasattr(hashlib, form) and getattr(hashlib, form)() or None if self.__digest is None: raise ValueError('Invalid hash type: {0}'.format(form)) self.__buff = buff def digest(self): ''' Get digest. :return: ''' return salt.utils.stringutils.to_str(self.__digest.hexdigest() + os.linesep)
saltstack/salt
salt/utils/hashutils.py
DigestCollector.digest
python
def digest(self): ''' Get digest. :return: ''' return salt.utils.stringutils.to_str(self.__digest.hexdigest() + os.linesep)
Get digest. :return:
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/hashutils.py#L200-L207
[ "def to_str(s, encoding=None, errors='strict', normalize=False):\n '''\n Given str, bytes, bytearray, or unicode (py2), return str\n '''\n def _normalize(s):\n try:\n return unicodedata.normalize('NFC', s) if normalize else s\n except TypeError:\n return s\n\n if encoding is None:\n # Try utf-8 first, and fall back to detected encoding\n encoding = ('utf-8', __salt_system_encoding__)\n if not isinstance(encoding, (tuple, list)):\n encoding = (encoding,)\n\n if not encoding:\n raise ValueError('encoding cannot be empty')\n\n # This shouldn't be six.string_types because if we're on PY2 and we already\n # have a string, we should just return it.\n if isinstance(s, str):\n return _normalize(s)\n\n exc = None\n if six.PY3:\n if isinstance(s, (bytes, bytearray)):\n for enc in encoding:\n try:\n return _normalize(s.decode(enc, errors))\n except UnicodeDecodeError as err:\n exc = err\n continue\n # The only way we get this far is if a UnicodeDecodeError was\n # raised, otherwise we would have already returned (or raised some\n # other exception).\n raise exc # pylint: disable=raising-bad-type\n raise TypeError('expected str, bytes, or bytearray not {}'.format(type(s)))\n else:\n if isinstance(s, bytearray):\n return str(s) # future lint: disable=blacklisted-function\n if isinstance(s, unicode): # pylint: disable=incompatible-py3-code,undefined-variable\n for enc in encoding:\n try:\n return _normalize(s).encode(enc, errors)\n except UnicodeEncodeError as err:\n exc = err\n continue\n # The only way we get this far is if a UnicodeDecodeError was\n # raised, otherwise we would have already returned (or raised some\n # other exception).\n raise exc # pylint: disable=raising-bad-type\n raise TypeError('expected str, bytearray, or unicode')\n" ]
class DigestCollector(object): ''' Class to collect digest of the file tree. ''' def __init__(self, form='sha256', buff=0x10000): ''' Constructor of the class. :param form: ''' self.__digest = hasattr(hashlib, form) and getattr(hashlib, form)() or None if self.__digest is None: raise ValueError('Invalid hash type: {0}'.format(form)) self.__buff = buff def add(self, path): ''' Update digest with the file content by path. :param path: :return: ''' with salt.utils.files.fopen(path, 'rb') as ifile: for chunk in iter(lambda: ifile.read(self.__buff), b''): self.__digest.update(chunk)
saltstack/salt
salt/modules/cassandra_cql.py
_load_properties
python
def _load_properties(property_name, config_option, set_default=False, default=None): ''' Load properties for the cassandra module from config or pillar. :param property_name: The property to load. :type property_name: str or list of str :param config_option: The name of the config option. :type config_option: str :param set_default: Should a default be set if not found in config. :type set_default: bool :param default: The default value to be set. :type default: str or int :return: The property fetched from the configuration or default. :rtype: str or list of str ''' if not property_name: log.debug("No property specified in function, trying to load from salt configuration") try: options = __salt__['config.option']('cassandra') except BaseException as e: log.error("Failed to get cassandra config options. Reason: %s", e) raise loaded_property = options.get(config_option) if not loaded_property: if set_default: log.debug('Setting default Cassandra %s to %s', config_option, default) loaded_property = default else: log.error('No cassandra %s specified in the configuration or passed to the module.', config_option) raise CommandExecutionError("ERROR: Cassandra {0} cannot be empty.".format(config_option)) return loaded_property return property_name
Load properties for the cassandra module from config or pillar. :param property_name: The property to load. :type property_name: str or list of str :param config_option: The name of the config option. :type config_option: str :param set_default: Should a default be set if not found in config. :type set_default: bool :param default: The default value to be set. :type default: str or int :return: The property fetched from the configuration or default. :rtype: str or list of str
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/cassandra_cql.py#L135-L167
null
# -*- coding: utf-8 -*- ''' Cassandra Database Module .. versionadded:: 2015.5.0 This module works with Cassandra v2 and v3 and hence generates queries based on the internal schema of said version. :depends: DataStax Python Driver for Apache Cassandra https://github.com/datastax/python-driver pip install cassandra-driver :referenced by: Salt's cassandra_cql returner :configuration: The Cassandra cluster members and connection port can either be specified in the master or minion config, the minion's pillar or be passed to the module. Example configuration in the config for a single node: .. code-block:: yaml cassandra: cluster: 192.168.50.10 port: 9000 Example configuration in the config for a cluster: .. code-block:: yaml cassandra: cluster: - 192.168.50.10 - 192.168.50.11 - 192.168.50.12 port: 9000 username: cas_admin .. versionchanged:: 2016.11.0 Added support for ``ssl_options`` and ``protocol_version``. Example configuration with `ssl options <http://datastax.github.io/python-driver/api/cassandra/cluster.html#cassandra.cluster.Cluster.ssl_options>`_: If ``ssl_options`` are present in cassandra config the cassandra_cql returner will use SSL. SSL isn't used if ``ssl_options`` isn't specified. .. code-block:: yaml cassandra: cluster: - 192.168.50.10 - 192.168.50.11 - 192.168.50.12 port: 9000 username: cas_admin ssl_options: ca_certs: /etc/ssl/certs/ca-bundle.trust.crt # SSL version should be one from the ssl module # This is an optional parameter ssl_version: PROTOCOL_TLSv1 Additionally you can also specify the ``protocol_version`` to `use <http://datastax.github.io/python-driver/api/cassandra/cluster.html#cassandra.cluster.Cluster.ssl_options>`_. .. code-block:: yaml cassandra: cluster: - 192.168.50.10 - 192.168.50.11 - 192.168.50.12 port: 9000 username: cas_admin # defaults to 4, if not set protocol_version: 3 ''' # Import Python Libs from __future__ import absolute_import, unicode_literals, print_function import logging import re import ssl # Import Salt Libs import salt.utils.json from salt.exceptions import CommandExecutionError # Import 3rd-party libs from salt.ext import six from salt.ext.six.moves import range import salt.utils.versions SSL_VERSION = 'ssl_version' log = logging.getLogger(__name__) __virtualname__ = 'cassandra_cql' HAS_DRIVER = False try: # pylint: disable=import-error,no-name-in-module from cassandra.cluster import Cluster from cassandra.cluster import NoHostAvailable from cassandra.connection import ConnectionException, \ ConnectionShutdown, OperationTimedOut from cassandra.auth import PlainTextAuthProvider from cassandra.query import dict_factory # pylint: enable=import-error,no-name-in-module HAS_DRIVER = True except ImportError: pass def __virtual__(): ''' Return virtual name of the module only if the python driver can be loaded. :return: The virtual name of the module. :rtype: str ''' if HAS_DRIVER: return __virtualname__ return (False, 'Cannot load cassandra_cql module: python driver not found') def _async_log_errors(errors): log.error('Cassandra_cql asynchronous call returned: %s', errors) def _get_ssl_opts(): ''' Parse out ssl_options for Cassandra cluster connection. Make sure that the ssl_version (if any specified) is valid. ''' sslopts = __salt__['config.option']('cassandra').get('ssl_options', None) ssl_opts = {} if sslopts: ssl_opts['ca_certs'] = sslopts['ca_certs'] if SSL_VERSION in sslopts: if not sslopts[SSL_VERSION].startswith('PROTOCOL_'): valid_opts = ', '.join( [x for x in dir(ssl) if x.startswith('PROTOCOL_')] ) raise CommandExecutionError('Invalid protocol_version ' 'specified! ' 'Please make sure ' 'that the ssl protocol' 'version is one from the SSL' 'module. ' 'Valid options are ' '{0}'.format(valid_opts)) else: ssl_opts[SSL_VERSION] = \ getattr(ssl, sslopts[SSL_VERSION]) return ssl_opts else: return None def _connect(contact_points=None, port=None, cql_user=None, cql_pass=None, protocol_version=None): ''' Connect to a Cassandra cluster. :param contact_points: The Cassandra cluster addresses, can either be a string or a list of IPs. :type contact_points: str or list of str :param cql_user: The Cassandra user if authentication is turned on. :type cql_user: str :param cql_pass: The Cassandra user password if authentication is turned on. :type cql_pass: str :param port: The Cassandra cluster port, defaults to None. :type port: int :param protocol_version: Cassandra protocol version to use. :type port: int :return: The session and cluster objects. :rtype: cluster object, session object ''' # Lazy load the Cassandra cluster and session for this module by creating a # cluster and session when cql_query is called the first time. Get the # Cassandra cluster and session from this module's __context__ after it is # loaded the first time cql_query is called. # # TODO: Call cluster.shutdown() when the module is unloaded on # master/minion shutdown. Currently, Master.shutdown() and Minion.shutdown() # do nothing to allow loaded modules to gracefully handle resources stored # in __context__ (i.e. connection pools). This means that the connection # pool is orphaned and Salt relies on Cassandra to reclaim connections. # Perhaps if Master/Minion daemons could be enhanced to call an "__unload__" # function, or something similar for each loaded module, connection pools # and the like can be gracefully reclaimed/shutdown. if (__context__ and 'cassandra_cql_returner_cluster' in __context__ and 'cassandra_cql_returner_session' in __context__): return __context__['cassandra_cql_returner_cluster'], __context__['cassandra_cql_returner_session'] else: contact_points = _load_properties(property_name=contact_points, config_option='cluster') contact_points = contact_points if isinstance(contact_points, list) else contact_points.split(',') port = _load_properties(property_name=port, config_option='port', set_default=True, default=9042) cql_user = _load_properties(property_name=cql_user, config_option='username', set_default=True, default="cassandra") cql_pass = _load_properties(property_name=cql_pass, config_option='password', set_default=True, default="cassandra") protocol_version = _load_properties(property_name=protocol_version, config_option='protocol_version', set_default=True, default=4) try: auth_provider = PlainTextAuthProvider(username=cql_user, password=cql_pass) ssl_opts = _get_ssl_opts() if ssl_opts: cluster = Cluster(contact_points, port=port, auth_provider=auth_provider, ssl_options=ssl_opts, protocol_version=protocol_version, compression=True) else: cluster = Cluster(contact_points, port=port, auth_provider=auth_provider, protocol_version=protocol_version, compression=True) for recontimes in range(1, 4): try: session = cluster.connect() break except OperationTimedOut: log.warning('Cassandra cluster.connect timed out, try %s', recontimes) if recontimes >= 3: raise # TODO: Call cluster.shutdown() when the module is unloaded on shutdown. __context__['cassandra_cql_returner_cluster'] = cluster __context__['cassandra_cql_returner_session'] = session __context__['cassandra_cql_prepared'] = {} log.debug('Successfully connected to Cassandra cluster at %s', contact_points) return cluster, session except TypeError: pass except (ConnectionException, ConnectionShutdown, NoHostAvailable): log.error('Could not connect to Cassandra cluster at %s', contact_points) raise CommandExecutionError('ERROR: Could not connect to Cassandra cluster.') def cql_query(query, contact_points=None, port=None, cql_user=None, cql_pass=None): ''' Run a query on a Cassandra cluster and return a dictionary. :param query: The query to execute. :type query: str :param contact_points: The Cassandra cluster addresses, can either be a string or a list of IPs. :type contact_points: str | list[str] :param cql_user: The Cassandra user if authentication is turned on. :type cql_user: str :param cql_pass: The Cassandra user password if authentication is turned on. :type cql_pass: str :param port: The Cassandra cluster port, defaults to None. :type port: int :param params: The parameters for the query, optional. :type params: str :return: A dictionary from the return values of the query :rtype: list[dict] CLI Example: .. code-block:: bash salt 'cassandra-server' cassandra_cql.cql_query "SELECT * FROM users_by_name WHERE first_name = 'jane'" ''' try: cluster, session = _connect(contact_points=contact_points, port=port, cql_user=cql_user, cql_pass=cql_pass) except CommandExecutionError: log.critical('Could not get Cassandra cluster session.') raise except BaseException as e: log.critical('Unexpected error while getting Cassandra cluster session: %s', e) raise session.row_factory = dict_factory ret = [] # Cassandra changed their internal schema from v2 to v3 # If the query contains a dictionary sorted by versions # Find the query for the current cluster version. # https://issues.apache.org/jira/browse/CASSANDRA-6717 if isinstance(query, dict): cluster_version = version(contact_points=contact_points, port=port, cql_user=cql_user, cql_pass=cql_pass) match = re.match(r'^(\d+)\.(\d+)(?:\.(\d+))?', cluster_version) major, minor, point = match.groups() # try to find the specific version in the query dictionary # then try the major version # otherwise default to the highest version number try: query = query[cluster_version] except KeyError: query = query.get(major, max(query)) log.debug('New query is: %s', query) try: results = session.execute(query) except BaseException as e: log.error('Failed to execute query: %s\n reason: %s', query, e) msg = "ERROR: Cassandra query failed: {0} reason: {1}".format(query, e) raise CommandExecutionError(msg) if results: for result in results: values = {} for key, value in six.iteritems(result): # Salt won't return dictionaries with odd types like uuid.UUID if not isinstance(value, six.text_type): # Must support Cassandra collection types. # Namely, Cassandras set, list, and map collections. if not isinstance(value, (set, list, dict)): value = six.text_type(value) values[key] = value ret.append(values) return ret def cql_query_with_prepare(query, statement_name, statement_arguments, callback_errors=None, contact_points=None, port=None, cql_user=None, cql_pass=None, **kwargs): ''' Run a query on a Cassandra cluster and return a dictionary. This function should not be used asynchronously for SELECTs -- it will not return anything and we don't currently have a mechanism for handling a future that will return results. :param query: The query to execute. :type query: str :param statement_name: Name to assign the prepared statement in the __context__ dictionary :type statement_name: str :param statement_arguments: Bind parameters for the SQL statement :type statement_arguments: list[str] :param async: Run this query in asynchronous mode :type async: bool :param callback_errors: Function to call after query runs if there is an error :type callback_errors: Function callable :param contact_points: The Cassandra cluster addresses, can either be a string or a list of IPs. :type contact_points: str | list[str] :param cql_user: The Cassandra user if authentication is turned on. :type cql_user: str :param cql_pass: The Cassandra user password if authentication is turned on. :type cql_pass: str :param port: The Cassandra cluster port, defaults to None. :type port: int :param params: The parameters for the query, optional. :type params: str :return: A dictionary from the return values of the query :rtype: list[dict] CLI Example: .. code-block:: bash # Insert data asynchronously salt this-node cassandra_cql.cql_query_with_prepare "name_insert" "INSERT INTO USERS (first_name, last_name) VALUES (?, ?)" \ statement_arguments=['John','Doe'], asynchronous=True # Select data, should not be asynchronous because there is not currently a facility to return data from a future salt this-node cassandra_cql.cql_query_with_prepare "name_select" "SELECT * FROM USERS WHERE first_name=?" \ statement_arguments=['John'] ''' # Backward-compatibility with Python 3.7: "async" is a reserved word asynchronous = kwargs.get('async', False) try: cluster, session = _connect(contact_points=contact_points, port=port, cql_user=cql_user, cql_pass=cql_pass) except CommandExecutionError: log.critical('Could not get Cassandra cluster session.') raise except BaseException as e: log.critical('Unexpected error while getting Cassandra cluster session: %s', e) raise if statement_name not in __context__['cassandra_cql_prepared']: try: bound_statement = session.prepare(query) __context__['cassandra_cql_prepared'][statement_name] = bound_statement except BaseException as e: log.critical('Unexpected error while preparing SQL statement: %s', e) raise else: bound_statement = __context__['cassandra_cql_prepared'][statement_name] session.row_factory = dict_factory ret = [] try: if asynchronous: future_results = session.execute_async(bound_statement.bind(statement_arguments)) # future_results.add_callbacks(_async_log_errors) else: results = session.execute(bound_statement.bind(statement_arguments)) except BaseException as e: log.error('Failed to execute query: %s\n reason: %s', query, e) msg = "ERROR: Cassandra query failed: {0} reason: {1}".format(query, e) raise CommandExecutionError(msg) if not asynchronous and results: for result in results: values = {} for key, value in six.iteritems(result): # Salt won't return dictionaries with odd types like uuid.UUID if not isinstance(value, six.text_type): # Must support Cassandra collection types. # Namely, Cassandras set, list, and map collections. if not isinstance(value, (set, list, dict)): value = six.text_type(value) values[key] = value ret.append(values) # If this was a synchronous call, then we either have an empty list # because there was no return, or we have a return # If this was an asynchronous call we only return the empty list return ret def version(contact_points=None, port=None, cql_user=None, cql_pass=None): ''' Show the Cassandra version. :param contact_points: The Cassandra cluster addresses, can either be a string or a list of IPs. :type contact_points: str | list[str] :param cql_user: The Cassandra user if authentication is turned on. :type cql_user: str :param cql_pass: The Cassandra user password if authentication is turned on. :type cql_pass: str :param port: The Cassandra cluster port, defaults to None. :type port: int :return: The version for this Cassandra cluster. :rtype: str CLI Example: .. code-block:: bash salt 'minion1' cassandra_cql.version salt 'minion1' cassandra_cql.version contact_points=minion1 ''' query = '''select release_version from system.local limit 1;''' try: ret = cql_query(query, contact_points, port, cql_user, cql_pass) except CommandExecutionError: log.critical('Could not get Cassandra version.') raise except BaseException as e: log.critical('Unexpected error while getting Cassandra version: %s', e) raise return ret[0].get('release_version') def info(contact_points=None, port=None, cql_user=None, cql_pass=None): ''' Show the Cassandra information for this cluster. :param contact_points: The Cassandra cluster addresses, can either be a string or a list of IPs. :type contact_points: str | list[str] :param cql_user: The Cassandra user if authentication is turned on. :type cql_user: str :param cql_pass: The Cassandra user password if authentication is turned on. :type cql_pass: str :param port: The Cassandra cluster port, defaults to None. :type port: int :return: The information for this Cassandra cluster. :rtype: dict CLI Example: .. code-block:: bash salt 'minion1' cassandra_cql.info salt 'minion1' cassandra_cql.info contact_points=minion1 ''' query = '''select cluster_name, data_center, partitioner, host_id, rack, release_version, cql_version, schema_version, thrift_version from system.local limit 1;''' ret = {} try: ret = cql_query(query, contact_points, port, cql_user, cql_pass) except CommandExecutionError: log.critical('Could not list Cassandra info.') raise except BaseException as e: log.critical('Unexpected error while listing Cassandra info: %s', e) raise return ret def list_keyspaces(contact_points=None, port=None, cql_user=None, cql_pass=None): ''' List keyspaces in a Cassandra cluster. :param contact_points: The Cassandra cluster addresses, can either be a string or a list of IPs. :type contact_points: str | list[str] :param cql_user: The Cassandra user if authentication is turned on. :type cql_user: str :param cql_pass: The Cassandra user password if authentication is turned on. :type cql_pass: str :param port: The Cassandra cluster port, defaults to None. :type port: int :return: The keyspaces in this Cassandra cluster. :rtype: list[dict] CLI Example: .. code-block:: bash salt 'minion1' cassandra_cql.list_keyspaces salt 'minion1' cassandra_cql.list_keyspaces contact_points=minion1 port=9000 ''' query = { '2': 'select keyspace_name from system.schema_keyspaces;', '3': 'select keyspace_name from system_schema.keyspaces;', } ret = {} try: ret = cql_query(query, contact_points, port, cql_user, cql_pass) except CommandExecutionError: log.critical('Could not list keyspaces.') raise except BaseException as e: log.critical('Unexpected error while listing keyspaces: %s', e) raise return ret def list_column_families(keyspace=None, contact_points=None, port=None, cql_user=None, cql_pass=None): ''' List column families in a Cassandra cluster for all keyspaces or just the provided one. :param keyspace: The keyspace to provide the column families for, optional. :type keyspace: str :param contact_points: The Cassandra cluster addresses, can either be a string or a list of IPs. :type contact_points: str | list[str] :param cql_user: The Cassandra user if authentication is turned on. :type cql_user: str :param cql_pass: The Cassandra user password if authentication is turned on. :type cql_pass: str :param port: The Cassandra cluster port, defaults to None. :type port: int :return: The column families in this Cassandra cluster. :rtype: list[dict] CLI Example: .. code-block:: bash salt 'minion1' cassandra_cql.list_column_families salt 'minion1' cassandra_cql.list_column_families contact_points=minion1 salt 'minion1' cassandra_cql.list_column_families keyspace=system ''' where_clause = "where keyspace_name = '{0}'".format(keyspace) if keyspace else "" query = { '2': '''select columnfamily_name from system.schema_columnfamilies {0};'''.format(where_clause), '3': '''select column_name from system_schema.columns {0};'''.format(where_clause), } ret = {} try: ret = cql_query(query, contact_points, port, cql_user, cql_pass) except CommandExecutionError: log.critical('Could not list column families.') raise except BaseException as e: log.critical('Unexpected error while listing column families: %s', e) raise return ret def keyspace_exists(keyspace, contact_points=None, port=None, cql_user=None, cql_pass=None): ''' Check if a keyspace exists in a Cassandra cluster. :param keyspace The keyspace name to check for. :type keyspace: str :param contact_points: The Cassandra cluster addresses, can either be a string or a list of IPs. :type contact_points: str | list[str] :param cql_user: The Cassandra user if authentication is turned on. :type cql_user: str :param cql_pass: The Cassandra user password if authentication is turned on. :type cql_pass: str :param port: The Cassandra cluster port, defaults to None. :type port: int :return: The info for the keyspace or False if it does not exist. :rtype: dict CLI Example: .. code-block:: bash salt 'minion1' cassandra_cql.keyspace_exists keyspace=system ''' query = { '2': '''select keyspace_name from system.schema_keyspaces where keyspace_name = '{0}';'''.format(keyspace), '3': '''select keyspace_name from system_schema.keyspaces where keyspace_name = '{0}';'''.format(keyspace), } try: ret = cql_query(query, contact_points, port, cql_user, cql_pass) except CommandExecutionError: log.critical('Could not determine if keyspace exists.') raise except BaseException as e: log.critical('Unexpected error while determining if keyspace exists: %s', e) raise return True if ret else False def create_keyspace(keyspace, replication_strategy='SimpleStrategy', replication_factor=1, replication_datacenters=None, contact_points=None, port=None, cql_user=None, cql_pass=None): ''' Create a new keyspace in Cassandra. :param keyspace: The keyspace name :type keyspace: str :param replication_strategy: either `SimpleStrategy` or `NetworkTopologyStrategy` :type replication_strategy: str :param replication_factor: number of replicas of data on multiple nodes. not used if using NetworkTopologyStrategy :type replication_factor: int :param replication_datacenters: string or dict of datacenter names to replication factors, required if using NetworkTopologyStrategy (will be a dict if coming from state file). :type replication_datacenters: str | dict[str, int] :param contact_points: The Cassandra cluster addresses, can either be a string or a list of IPs. :type contact_points: str | list[str] :param cql_user: The Cassandra user if authentication is turned on. :type cql_user: str :param cql_pass: The Cassandra user password if authentication is turned on. :type cql_pass: str :param port: The Cassandra cluster port, defaults to None. :type port: int :return: The info for the keyspace or False if it does not exist. :rtype: dict CLI Example: .. code-block:: bash # CLI Example: salt 'minion1' cassandra_cql.create_keyspace keyspace=newkeyspace salt 'minion1' cassandra_cql.create_keyspace keyspace=newkeyspace replication_strategy=NetworkTopologyStrategy \ replication_datacenters='{"datacenter_1": 3, "datacenter_2": 2}' ''' existing_keyspace = keyspace_exists(keyspace, contact_points, port) if not existing_keyspace: # Add the strategy, replication_factor, etc. replication_map = { 'class': replication_strategy } if replication_datacenters: if isinstance(replication_datacenters, six.string_types): try: replication_datacenter_map = salt.utils.json.loads(replication_datacenters) replication_map.update(**replication_datacenter_map) except BaseException: # pylint: disable=W0703 log.error("Could not load json replication_datacenters.") return False else: replication_map.update(**replication_datacenters) else: replication_map['replication_factor'] = replication_factor query = '''create keyspace {0} with replication = {1} and durable_writes = true;'''.format(keyspace, replication_map) try: cql_query(query, contact_points, port, cql_user, cql_pass) except CommandExecutionError: log.critical('Could not create keyspace.') raise except BaseException as e: log.critical('Unexpected error while creating keyspace: %s', e) raise def drop_keyspace(keyspace, contact_points=None, port=None, cql_user=None, cql_pass=None): ''' Drop a keyspace if it exists in a Cassandra cluster. :param keyspace: The keyspace to drop. :type keyspace: str :param contact_points: The Cassandra cluster addresses, can either be a string or a list of IPs. :type contact_points: str | list[str] :param cql_user: The Cassandra user if authentication is turned on. :type cql_user: str :param cql_pass: The Cassandra user password if authentication is turned on. :type cql_pass: str :param port: The Cassandra cluster port, defaults to None. :type port: int :return: The info for the keyspace or False if it does not exist. :rtype: dict CLI Example: .. code-block:: bash salt 'minion1' cassandra_cql.drop_keyspace keyspace=test salt 'minion1' cassandra_cql.drop_keyspace keyspace=test contact_points=minion1 ''' existing_keyspace = keyspace_exists(keyspace, contact_points, port) if existing_keyspace: query = '''drop keyspace {0};'''.format(keyspace) try: cql_query(query, contact_points, port, cql_user, cql_pass) except CommandExecutionError: log.critical('Could not drop keyspace.') raise except BaseException as e: log.critical('Unexpected error while dropping keyspace: %s', e) raise return True def list_users(contact_points=None, port=None, cql_user=None, cql_pass=None): ''' List existing users in this Cassandra cluster. :param contact_points: The Cassandra cluster addresses, can either be a string or a list of IPs. :type contact_points: str | list[str] :param port: The Cassandra cluster port, defaults to None. :type port: int :param cql_user: The Cassandra user if authentication is turned on. :type cql_user: str :param cql_pass: The Cassandra user password if authentication is turned on. :type cql_pass: str :return: The list of existing users. :rtype: dict CLI Example: .. code-block:: bash salt 'minion1' cassandra_cql.list_users salt 'minion1' cassandra_cql.list_users contact_points=minion1 ''' query = "list users;" ret = {} try: ret = cql_query(query, contact_points, port, cql_user, cql_pass) except CommandExecutionError: log.critical('Could not list users.') raise except BaseException as e: log.critical('Unexpected error while listing users: %s', e) raise return ret def create_user(username, password, superuser=False, contact_points=None, port=None, cql_user=None, cql_pass=None): ''' Create a new cassandra user with credentials and superuser status. :param username: The name of the new user. :type username: str :param password: The password of the new user. :type password: str :param superuser: Is the new user going to be a superuser? default: False :type superuser: bool :param contact_points: The Cassandra cluster addresses, can either be a string or a list of IPs. :type contact_points: str | list[str] :param cql_user: The Cassandra user if authentication is turned on. :type cql_user: str :param cql_pass: The Cassandra user password if authentication is turned on. :type cql_pass: str :param port: The Cassandra cluster port, defaults to None. :type port: int :return: :rtype: CLI Example: .. code-block:: bash salt 'minion1' cassandra_cql.create_user username=joe password=secret salt 'minion1' cassandra_cql.create_user username=joe password=secret superuser=True salt 'minion1' cassandra_cql.create_user username=joe password=secret superuser=True contact_points=minion1 ''' superuser_cql = 'superuser' if superuser else 'nosuperuser' query = '''create user if not exists {0} with password '{1}' {2};'''.format(username, password, superuser_cql) log.debug("Attempting to create a new user with username=%s superuser=%s", username, superuser_cql) # The create user query doesn't actually return anything if the query succeeds. # If the query fails, catch the exception, log a messange and raise it again. try: cql_query(query, contact_points, port, cql_user, cql_pass) except CommandExecutionError: log.critical('Could not create user.') raise except BaseException as e: log.critical('Unexpected error while creating user: %s', e) raise return True def create_role(username, password, superuser=False, login=False, contact_points=None, port=None, cql_user=None, cql_pass=None): ''' Create a new cassandra role with credentials and superuser status. :param username: The name of the new user. :type username: str :param password: The password of the new user. :type password: str :param superuser: Is the new role going to be a superuser? default: False :type superuser: bool :param login: Is the new role going to be allowed to log in? default: False :type superuser: bool :param contact_points: The Cassandra cluster addresses, can either be a string or a list of IPs. :type contact_points: str | list[str] :param cql_user: The Cassandra user if authentication is turned on. :type cql_user: str :param cql_pass: The Cassandra user password if authentication is turned on. :type cql_pass: str :param port: The Cassandra cluster port, defaults to None. :type port: int :return: :rtype: CLI Example: .. code-block:: bash salt 'minion1' cassandra_cql.create_role username=joe password=secret salt 'minion1' cassandra_cql.create_role username=joe password=secret superuser=True salt 'minion1' cassandra_cql.create_role username=joe password=secret superuser=True login=True salt 'minion1' cassandra_cql.create_role username=joe password=secret superuser=True login=True contact_points=minion1 ''' superuser_cql = 'superuser = true' if superuser else 'superuser = false' login_cql = 'login = true' if login else 'login = false' query = '''create role if not exists {0} with password '{1}' and {2} and {3} ;'''.format(username, password, superuser_cql, login_cql) log.debug("Attempting to create a new role with username=%s superuser=%s login=%s", username, superuser, login) # The create role query doesn't actually return anything if the query succeeds. # If the query fails, catch the exception, log a messange and raise it again. try: cql_query(query, contact_points, port, cql_user, cql_pass) except CommandExecutionError: log.critical('Could not create role.') raise except BaseException as e: log.critical('Unexpected error while creating role: %s', e) raise return True def list_permissions(username=None, resource=None, resource_type='keyspace', permission=None, contact_points=None, port=None, cql_user=None, cql_pass=None): ''' List permissions. :param username: The name of the user to list permissions for. :type username: str :param resource: The resource (keyspace or table), if None, permissions for all resources are listed. :type resource: str :param resource_type: The resource_type (keyspace or table), defaults to 'keyspace'. :type resource_type: str :param permission: A permission name (e.g. select), if None, all permissions are listed. :type permission: str :param contact_points: The Cassandra cluster addresses, can either be a string or a list of IPs. :type contact_points: str | list[str] :param cql_user: The Cassandra user if authentication is turned on. :type cql_user: str :param cql_pass: The Cassandra user password if authentication is turned on. :type cql_pass: str :param port: The Cassandra cluster port, defaults to None. :type port: int :return: Dictionary of permissions. :rtype: dict CLI Example: .. code-block:: bash salt 'minion1' cassandra_cql.list_permissions salt 'minion1' cassandra_cql.list_permissions username=joe resource=test_keyspace permission=select salt 'minion1' cassandra_cql.list_permissions username=joe resource=test_table resource_type=table \ permission=select contact_points=minion1 ''' keyspace_cql = "{0} {1}".format(resource_type, resource) if resource else "all keyspaces" permission_cql = "{0} permission".format(permission) if permission else "all permissions" query = "list {0} on {1}".format(permission_cql, keyspace_cql) if username: query = "{0} of {1}".format(query, username) log.debug("Attempting to list permissions with query '%s'", query) ret = {} try: ret = cql_query(query, contact_points, port, cql_user, cql_pass) except CommandExecutionError: log.critical('Could not list permissions.') raise except BaseException as e: log.critical('Unexpected error while listing permissions: %s', e) raise return ret def grant_permission(username, resource=None, resource_type='keyspace', permission=None, contact_points=None, port=None, cql_user=None, cql_pass=None): ''' Grant permissions to a user. :param username: The name of the user to grant permissions to. :type username: str :param resource: The resource (keyspace or table), if None, permissions for all resources are granted. :type resource: str :param resource_type: The resource_type (keyspace or table), defaults to 'keyspace'. :type resource_type: str :param permission: A permission name (e.g. select), if None, all permissions are granted. :type permission: str :param contact_points: The Cassandra cluster addresses, can either be a string or a list of IPs. :type contact_points: str | list[str] :param cql_user: The Cassandra user if authentication is turned on. :type cql_user: str :param cql_pass: The Cassandra user password if authentication is turned on. :type cql_pass: str :param port: The Cassandra cluster port, defaults to None. :type port: int :return: :rtype: CLI Example: .. code-block:: bash salt 'minion1' cassandra_cql.grant_permission salt 'minion1' cassandra_cql.grant_permission username=joe resource=test_keyspace permission=select salt 'minion1' cassandra_cql.grant_permission username=joe resource=test_table resource_type=table \ permission=select contact_points=minion1 ''' permission_cql = "grant {0}".format(permission) if permission else "grant all permissions" resource_cql = "on {0} {1}".format(resource_type, resource) if resource else "on all keyspaces" query = "{0} {1} to {2}".format(permission_cql, resource_cql, username) log.debug("Attempting to grant permissions with query '%s'", query) try: cql_query(query, contact_points, port, cql_user, cql_pass) except CommandExecutionError: log.critical('Could not grant permissions.') raise except BaseException as e: log.critical('Unexpected error while granting permissions: %s', e) raise return True
saltstack/salt
salt/modules/cassandra_cql.py
_get_ssl_opts
python
def _get_ssl_opts(): ''' Parse out ssl_options for Cassandra cluster connection. Make sure that the ssl_version (if any specified) is valid. ''' sslopts = __salt__['config.option']('cassandra').get('ssl_options', None) ssl_opts = {} if sslopts: ssl_opts['ca_certs'] = sslopts['ca_certs'] if SSL_VERSION in sslopts: if not sslopts[SSL_VERSION].startswith('PROTOCOL_'): valid_opts = ', '.join( [x for x in dir(ssl) if x.startswith('PROTOCOL_')] ) raise CommandExecutionError('Invalid protocol_version ' 'specified! ' 'Please make sure ' 'that the ssl protocol' 'version is one from the SSL' 'module. ' 'Valid options are ' '{0}'.format(valid_opts)) else: ssl_opts[SSL_VERSION] = \ getattr(ssl, sslopts[SSL_VERSION]) return ssl_opts else: return None
Parse out ssl_options for Cassandra cluster connection. Make sure that the ssl_version (if any specified) is valid.
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/cassandra_cql.py#L170-L198
null
# -*- coding: utf-8 -*- ''' Cassandra Database Module .. versionadded:: 2015.5.0 This module works with Cassandra v2 and v3 and hence generates queries based on the internal schema of said version. :depends: DataStax Python Driver for Apache Cassandra https://github.com/datastax/python-driver pip install cassandra-driver :referenced by: Salt's cassandra_cql returner :configuration: The Cassandra cluster members and connection port can either be specified in the master or minion config, the minion's pillar or be passed to the module. Example configuration in the config for a single node: .. code-block:: yaml cassandra: cluster: 192.168.50.10 port: 9000 Example configuration in the config for a cluster: .. code-block:: yaml cassandra: cluster: - 192.168.50.10 - 192.168.50.11 - 192.168.50.12 port: 9000 username: cas_admin .. versionchanged:: 2016.11.0 Added support for ``ssl_options`` and ``protocol_version``. Example configuration with `ssl options <http://datastax.github.io/python-driver/api/cassandra/cluster.html#cassandra.cluster.Cluster.ssl_options>`_: If ``ssl_options`` are present in cassandra config the cassandra_cql returner will use SSL. SSL isn't used if ``ssl_options`` isn't specified. .. code-block:: yaml cassandra: cluster: - 192.168.50.10 - 192.168.50.11 - 192.168.50.12 port: 9000 username: cas_admin ssl_options: ca_certs: /etc/ssl/certs/ca-bundle.trust.crt # SSL version should be one from the ssl module # This is an optional parameter ssl_version: PROTOCOL_TLSv1 Additionally you can also specify the ``protocol_version`` to `use <http://datastax.github.io/python-driver/api/cassandra/cluster.html#cassandra.cluster.Cluster.ssl_options>`_. .. code-block:: yaml cassandra: cluster: - 192.168.50.10 - 192.168.50.11 - 192.168.50.12 port: 9000 username: cas_admin # defaults to 4, if not set protocol_version: 3 ''' # Import Python Libs from __future__ import absolute_import, unicode_literals, print_function import logging import re import ssl # Import Salt Libs import salt.utils.json from salt.exceptions import CommandExecutionError # Import 3rd-party libs from salt.ext import six from salt.ext.six.moves import range import salt.utils.versions SSL_VERSION = 'ssl_version' log = logging.getLogger(__name__) __virtualname__ = 'cassandra_cql' HAS_DRIVER = False try: # pylint: disable=import-error,no-name-in-module from cassandra.cluster import Cluster from cassandra.cluster import NoHostAvailable from cassandra.connection import ConnectionException, \ ConnectionShutdown, OperationTimedOut from cassandra.auth import PlainTextAuthProvider from cassandra.query import dict_factory # pylint: enable=import-error,no-name-in-module HAS_DRIVER = True except ImportError: pass def __virtual__(): ''' Return virtual name of the module only if the python driver can be loaded. :return: The virtual name of the module. :rtype: str ''' if HAS_DRIVER: return __virtualname__ return (False, 'Cannot load cassandra_cql module: python driver not found') def _async_log_errors(errors): log.error('Cassandra_cql asynchronous call returned: %s', errors) def _load_properties(property_name, config_option, set_default=False, default=None): ''' Load properties for the cassandra module from config or pillar. :param property_name: The property to load. :type property_name: str or list of str :param config_option: The name of the config option. :type config_option: str :param set_default: Should a default be set if not found in config. :type set_default: bool :param default: The default value to be set. :type default: str or int :return: The property fetched from the configuration or default. :rtype: str or list of str ''' if not property_name: log.debug("No property specified in function, trying to load from salt configuration") try: options = __salt__['config.option']('cassandra') except BaseException as e: log.error("Failed to get cassandra config options. Reason: %s", e) raise loaded_property = options.get(config_option) if not loaded_property: if set_default: log.debug('Setting default Cassandra %s to %s', config_option, default) loaded_property = default else: log.error('No cassandra %s specified in the configuration or passed to the module.', config_option) raise CommandExecutionError("ERROR: Cassandra {0} cannot be empty.".format(config_option)) return loaded_property return property_name def _connect(contact_points=None, port=None, cql_user=None, cql_pass=None, protocol_version=None): ''' Connect to a Cassandra cluster. :param contact_points: The Cassandra cluster addresses, can either be a string or a list of IPs. :type contact_points: str or list of str :param cql_user: The Cassandra user if authentication is turned on. :type cql_user: str :param cql_pass: The Cassandra user password if authentication is turned on. :type cql_pass: str :param port: The Cassandra cluster port, defaults to None. :type port: int :param protocol_version: Cassandra protocol version to use. :type port: int :return: The session and cluster objects. :rtype: cluster object, session object ''' # Lazy load the Cassandra cluster and session for this module by creating a # cluster and session when cql_query is called the first time. Get the # Cassandra cluster and session from this module's __context__ after it is # loaded the first time cql_query is called. # # TODO: Call cluster.shutdown() when the module is unloaded on # master/minion shutdown. Currently, Master.shutdown() and Minion.shutdown() # do nothing to allow loaded modules to gracefully handle resources stored # in __context__ (i.e. connection pools). This means that the connection # pool is orphaned and Salt relies on Cassandra to reclaim connections. # Perhaps if Master/Minion daemons could be enhanced to call an "__unload__" # function, or something similar for each loaded module, connection pools # and the like can be gracefully reclaimed/shutdown. if (__context__ and 'cassandra_cql_returner_cluster' in __context__ and 'cassandra_cql_returner_session' in __context__): return __context__['cassandra_cql_returner_cluster'], __context__['cassandra_cql_returner_session'] else: contact_points = _load_properties(property_name=contact_points, config_option='cluster') contact_points = contact_points if isinstance(contact_points, list) else contact_points.split(',') port = _load_properties(property_name=port, config_option='port', set_default=True, default=9042) cql_user = _load_properties(property_name=cql_user, config_option='username', set_default=True, default="cassandra") cql_pass = _load_properties(property_name=cql_pass, config_option='password', set_default=True, default="cassandra") protocol_version = _load_properties(property_name=protocol_version, config_option='protocol_version', set_default=True, default=4) try: auth_provider = PlainTextAuthProvider(username=cql_user, password=cql_pass) ssl_opts = _get_ssl_opts() if ssl_opts: cluster = Cluster(contact_points, port=port, auth_provider=auth_provider, ssl_options=ssl_opts, protocol_version=protocol_version, compression=True) else: cluster = Cluster(contact_points, port=port, auth_provider=auth_provider, protocol_version=protocol_version, compression=True) for recontimes in range(1, 4): try: session = cluster.connect() break except OperationTimedOut: log.warning('Cassandra cluster.connect timed out, try %s', recontimes) if recontimes >= 3: raise # TODO: Call cluster.shutdown() when the module is unloaded on shutdown. __context__['cassandra_cql_returner_cluster'] = cluster __context__['cassandra_cql_returner_session'] = session __context__['cassandra_cql_prepared'] = {} log.debug('Successfully connected to Cassandra cluster at %s', contact_points) return cluster, session except TypeError: pass except (ConnectionException, ConnectionShutdown, NoHostAvailable): log.error('Could not connect to Cassandra cluster at %s', contact_points) raise CommandExecutionError('ERROR: Could not connect to Cassandra cluster.') def cql_query(query, contact_points=None, port=None, cql_user=None, cql_pass=None): ''' Run a query on a Cassandra cluster and return a dictionary. :param query: The query to execute. :type query: str :param contact_points: The Cassandra cluster addresses, can either be a string or a list of IPs. :type contact_points: str | list[str] :param cql_user: The Cassandra user if authentication is turned on. :type cql_user: str :param cql_pass: The Cassandra user password if authentication is turned on. :type cql_pass: str :param port: The Cassandra cluster port, defaults to None. :type port: int :param params: The parameters for the query, optional. :type params: str :return: A dictionary from the return values of the query :rtype: list[dict] CLI Example: .. code-block:: bash salt 'cassandra-server' cassandra_cql.cql_query "SELECT * FROM users_by_name WHERE first_name = 'jane'" ''' try: cluster, session = _connect(contact_points=contact_points, port=port, cql_user=cql_user, cql_pass=cql_pass) except CommandExecutionError: log.critical('Could not get Cassandra cluster session.') raise except BaseException as e: log.critical('Unexpected error while getting Cassandra cluster session: %s', e) raise session.row_factory = dict_factory ret = [] # Cassandra changed their internal schema from v2 to v3 # If the query contains a dictionary sorted by versions # Find the query for the current cluster version. # https://issues.apache.org/jira/browse/CASSANDRA-6717 if isinstance(query, dict): cluster_version = version(contact_points=contact_points, port=port, cql_user=cql_user, cql_pass=cql_pass) match = re.match(r'^(\d+)\.(\d+)(?:\.(\d+))?', cluster_version) major, minor, point = match.groups() # try to find the specific version in the query dictionary # then try the major version # otherwise default to the highest version number try: query = query[cluster_version] except KeyError: query = query.get(major, max(query)) log.debug('New query is: %s', query) try: results = session.execute(query) except BaseException as e: log.error('Failed to execute query: %s\n reason: %s', query, e) msg = "ERROR: Cassandra query failed: {0} reason: {1}".format(query, e) raise CommandExecutionError(msg) if results: for result in results: values = {} for key, value in six.iteritems(result): # Salt won't return dictionaries with odd types like uuid.UUID if not isinstance(value, six.text_type): # Must support Cassandra collection types. # Namely, Cassandras set, list, and map collections. if not isinstance(value, (set, list, dict)): value = six.text_type(value) values[key] = value ret.append(values) return ret def cql_query_with_prepare(query, statement_name, statement_arguments, callback_errors=None, contact_points=None, port=None, cql_user=None, cql_pass=None, **kwargs): ''' Run a query on a Cassandra cluster and return a dictionary. This function should not be used asynchronously for SELECTs -- it will not return anything and we don't currently have a mechanism for handling a future that will return results. :param query: The query to execute. :type query: str :param statement_name: Name to assign the prepared statement in the __context__ dictionary :type statement_name: str :param statement_arguments: Bind parameters for the SQL statement :type statement_arguments: list[str] :param async: Run this query in asynchronous mode :type async: bool :param callback_errors: Function to call after query runs if there is an error :type callback_errors: Function callable :param contact_points: The Cassandra cluster addresses, can either be a string or a list of IPs. :type contact_points: str | list[str] :param cql_user: The Cassandra user if authentication is turned on. :type cql_user: str :param cql_pass: The Cassandra user password if authentication is turned on. :type cql_pass: str :param port: The Cassandra cluster port, defaults to None. :type port: int :param params: The parameters for the query, optional. :type params: str :return: A dictionary from the return values of the query :rtype: list[dict] CLI Example: .. code-block:: bash # Insert data asynchronously salt this-node cassandra_cql.cql_query_with_prepare "name_insert" "INSERT INTO USERS (first_name, last_name) VALUES (?, ?)" \ statement_arguments=['John','Doe'], asynchronous=True # Select data, should not be asynchronous because there is not currently a facility to return data from a future salt this-node cassandra_cql.cql_query_with_prepare "name_select" "SELECT * FROM USERS WHERE first_name=?" \ statement_arguments=['John'] ''' # Backward-compatibility with Python 3.7: "async" is a reserved word asynchronous = kwargs.get('async', False) try: cluster, session = _connect(contact_points=contact_points, port=port, cql_user=cql_user, cql_pass=cql_pass) except CommandExecutionError: log.critical('Could not get Cassandra cluster session.') raise except BaseException as e: log.critical('Unexpected error while getting Cassandra cluster session: %s', e) raise if statement_name not in __context__['cassandra_cql_prepared']: try: bound_statement = session.prepare(query) __context__['cassandra_cql_prepared'][statement_name] = bound_statement except BaseException as e: log.critical('Unexpected error while preparing SQL statement: %s', e) raise else: bound_statement = __context__['cassandra_cql_prepared'][statement_name] session.row_factory = dict_factory ret = [] try: if asynchronous: future_results = session.execute_async(bound_statement.bind(statement_arguments)) # future_results.add_callbacks(_async_log_errors) else: results = session.execute(bound_statement.bind(statement_arguments)) except BaseException as e: log.error('Failed to execute query: %s\n reason: %s', query, e) msg = "ERROR: Cassandra query failed: {0} reason: {1}".format(query, e) raise CommandExecutionError(msg) if not asynchronous and results: for result in results: values = {} for key, value in six.iteritems(result): # Salt won't return dictionaries with odd types like uuid.UUID if not isinstance(value, six.text_type): # Must support Cassandra collection types. # Namely, Cassandras set, list, and map collections. if not isinstance(value, (set, list, dict)): value = six.text_type(value) values[key] = value ret.append(values) # If this was a synchronous call, then we either have an empty list # because there was no return, or we have a return # If this was an asynchronous call we only return the empty list return ret def version(contact_points=None, port=None, cql_user=None, cql_pass=None): ''' Show the Cassandra version. :param contact_points: The Cassandra cluster addresses, can either be a string or a list of IPs. :type contact_points: str | list[str] :param cql_user: The Cassandra user if authentication is turned on. :type cql_user: str :param cql_pass: The Cassandra user password if authentication is turned on. :type cql_pass: str :param port: The Cassandra cluster port, defaults to None. :type port: int :return: The version for this Cassandra cluster. :rtype: str CLI Example: .. code-block:: bash salt 'minion1' cassandra_cql.version salt 'minion1' cassandra_cql.version contact_points=minion1 ''' query = '''select release_version from system.local limit 1;''' try: ret = cql_query(query, contact_points, port, cql_user, cql_pass) except CommandExecutionError: log.critical('Could not get Cassandra version.') raise except BaseException as e: log.critical('Unexpected error while getting Cassandra version: %s', e) raise return ret[0].get('release_version') def info(contact_points=None, port=None, cql_user=None, cql_pass=None): ''' Show the Cassandra information for this cluster. :param contact_points: The Cassandra cluster addresses, can either be a string or a list of IPs. :type contact_points: str | list[str] :param cql_user: The Cassandra user if authentication is turned on. :type cql_user: str :param cql_pass: The Cassandra user password if authentication is turned on. :type cql_pass: str :param port: The Cassandra cluster port, defaults to None. :type port: int :return: The information for this Cassandra cluster. :rtype: dict CLI Example: .. code-block:: bash salt 'minion1' cassandra_cql.info salt 'minion1' cassandra_cql.info contact_points=minion1 ''' query = '''select cluster_name, data_center, partitioner, host_id, rack, release_version, cql_version, schema_version, thrift_version from system.local limit 1;''' ret = {} try: ret = cql_query(query, contact_points, port, cql_user, cql_pass) except CommandExecutionError: log.critical('Could not list Cassandra info.') raise except BaseException as e: log.critical('Unexpected error while listing Cassandra info: %s', e) raise return ret def list_keyspaces(contact_points=None, port=None, cql_user=None, cql_pass=None): ''' List keyspaces in a Cassandra cluster. :param contact_points: The Cassandra cluster addresses, can either be a string or a list of IPs. :type contact_points: str | list[str] :param cql_user: The Cassandra user if authentication is turned on. :type cql_user: str :param cql_pass: The Cassandra user password if authentication is turned on. :type cql_pass: str :param port: The Cassandra cluster port, defaults to None. :type port: int :return: The keyspaces in this Cassandra cluster. :rtype: list[dict] CLI Example: .. code-block:: bash salt 'minion1' cassandra_cql.list_keyspaces salt 'minion1' cassandra_cql.list_keyspaces contact_points=minion1 port=9000 ''' query = { '2': 'select keyspace_name from system.schema_keyspaces;', '3': 'select keyspace_name from system_schema.keyspaces;', } ret = {} try: ret = cql_query(query, contact_points, port, cql_user, cql_pass) except CommandExecutionError: log.critical('Could not list keyspaces.') raise except BaseException as e: log.critical('Unexpected error while listing keyspaces: %s', e) raise return ret def list_column_families(keyspace=None, contact_points=None, port=None, cql_user=None, cql_pass=None): ''' List column families in a Cassandra cluster for all keyspaces or just the provided one. :param keyspace: The keyspace to provide the column families for, optional. :type keyspace: str :param contact_points: The Cassandra cluster addresses, can either be a string or a list of IPs. :type contact_points: str | list[str] :param cql_user: The Cassandra user if authentication is turned on. :type cql_user: str :param cql_pass: The Cassandra user password if authentication is turned on. :type cql_pass: str :param port: The Cassandra cluster port, defaults to None. :type port: int :return: The column families in this Cassandra cluster. :rtype: list[dict] CLI Example: .. code-block:: bash salt 'minion1' cassandra_cql.list_column_families salt 'minion1' cassandra_cql.list_column_families contact_points=minion1 salt 'minion1' cassandra_cql.list_column_families keyspace=system ''' where_clause = "where keyspace_name = '{0}'".format(keyspace) if keyspace else "" query = { '2': '''select columnfamily_name from system.schema_columnfamilies {0};'''.format(where_clause), '3': '''select column_name from system_schema.columns {0};'''.format(where_clause), } ret = {} try: ret = cql_query(query, contact_points, port, cql_user, cql_pass) except CommandExecutionError: log.critical('Could not list column families.') raise except BaseException as e: log.critical('Unexpected error while listing column families: %s', e) raise return ret def keyspace_exists(keyspace, contact_points=None, port=None, cql_user=None, cql_pass=None): ''' Check if a keyspace exists in a Cassandra cluster. :param keyspace The keyspace name to check for. :type keyspace: str :param contact_points: The Cassandra cluster addresses, can either be a string or a list of IPs. :type contact_points: str | list[str] :param cql_user: The Cassandra user if authentication is turned on. :type cql_user: str :param cql_pass: The Cassandra user password if authentication is turned on. :type cql_pass: str :param port: The Cassandra cluster port, defaults to None. :type port: int :return: The info for the keyspace or False if it does not exist. :rtype: dict CLI Example: .. code-block:: bash salt 'minion1' cassandra_cql.keyspace_exists keyspace=system ''' query = { '2': '''select keyspace_name from system.schema_keyspaces where keyspace_name = '{0}';'''.format(keyspace), '3': '''select keyspace_name from system_schema.keyspaces where keyspace_name = '{0}';'''.format(keyspace), } try: ret = cql_query(query, contact_points, port, cql_user, cql_pass) except CommandExecutionError: log.critical('Could not determine if keyspace exists.') raise except BaseException as e: log.critical('Unexpected error while determining if keyspace exists: %s', e) raise return True if ret else False def create_keyspace(keyspace, replication_strategy='SimpleStrategy', replication_factor=1, replication_datacenters=None, contact_points=None, port=None, cql_user=None, cql_pass=None): ''' Create a new keyspace in Cassandra. :param keyspace: The keyspace name :type keyspace: str :param replication_strategy: either `SimpleStrategy` or `NetworkTopologyStrategy` :type replication_strategy: str :param replication_factor: number of replicas of data on multiple nodes. not used if using NetworkTopologyStrategy :type replication_factor: int :param replication_datacenters: string or dict of datacenter names to replication factors, required if using NetworkTopologyStrategy (will be a dict if coming from state file). :type replication_datacenters: str | dict[str, int] :param contact_points: The Cassandra cluster addresses, can either be a string or a list of IPs. :type contact_points: str | list[str] :param cql_user: The Cassandra user if authentication is turned on. :type cql_user: str :param cql_pass: The Cassandra user password if authentication is turned on. :type cql_pass: str :param port: The Cassandra cluster port, defaults to None. :type port: int :return: The info for the keyspace or False if it does not exist. :rtype: dict CLI Example: .. code-block:: bash # CLI Example: salt 'minion1' cassandra_cql.create_keyspace keyspace=newkeyspace salt 'minion1' cassandra_cql.create_keyspace keyspace=newkeyspace replication_strategy=NetworkTopologyStrategy \ replication_datacenters='{"datacenter_1": 3, "datacenter_2": 2}' ''' existing_keyspace = keyspace_exists(keyspace, contact_points, port) if not existing_keyspace: # Add the strategy, replication_factor, etc. replication_map = { 'class': replication_strategy } if replication_datacenters: if isinstance(replication_datacenters, six.string_types): try: replication_datacenter_map = salt.utils.json.loads(replication_datacenters) replication_map.update(**replication_datacenter_map) except BaseException: # pylint: disable=W0703 log.error("Could not load json replication_datacenters.") return False else: replication_map.update(**replication_datacenters) else: replication_map['replication_factor'] = replication_factor query = '''create keyspace {0} with replication = {1} and durable_writes = true;'''.format(keyspace, replication_map) try: cql_query(query, contact_points, port, cql_user, cql_pass) except CommandExecutionError: log.critical('Could not create keyspace.') raise except BaseException as e: log.critical('Unexpected error while creating keyspace: %s', e) raise def drop_keyspace(keyspace, contact_points=None, port=None, cql_user=None, cql_pass=None): ''' Drop a keyspace if it exists in a Cassandra cluster. :param keyspace: The keyspace to drop. :type keyspace: str :param contact_points: The Cassandra cluster addresses, can either be a string or a list of IPs. :type contact_points: str | list[str] :param cql_user: The Cassandra user if authentication is turned on. :type cql_user: str :param cql_pass: The Cassandra user password if authentication is turned on. :type cql_pass: str :param port: The Cassandra cluster port, defaults to None. :type port: int :return: The info for the keyspace or False if it does not exist. :rtype: dict CLI Example: .. code-block:: bash salt 'minion1' cassandra_cql.drop_keyspace keyspace=test salt 'minion1' cassandra_cql.drop_keyspace keyspace=test contact_points=minion1 ''' existing_keyspace = keyspace_exists(keyspace, contact_points, port) if existing_keyspace: query = '''drop keyspace {0};'''.format(keyspace) try: cql_query(query, contact_points, port, cql_user, cql_pass) except CommandExecutionError: log.critical('Could not drop keyspace.') raise except BaseException as e: log.critical('Unexpected error while dropping keyspace: %s', e) raise return True def list_users(contact_points=None, port=None, cql_user=None, cql_pass=None): ''' List existing users in this Cassandra cluster. :param contact_points: The Cassandra cluster addresses, can either be a string or a list of IPs. :type contact_points: str | list[str] :param port: The Cassandra cluster port, defaults to None. :type port: int :param cql_user: The Cassandra user if authentication is turned on. :type cql_user: str :param cql_pass: The Cassandra user password if authentication is turned on. :type cql_pass: str :return: The list of existing users. :rtype: dict CLI Example: .. code-block:: bash salt 'minion1' cassandra_cql.list_users salt 'minion1' cassandra_cql.list_users contact_points=minion1 ''' query = "list users;" ret = {} try: ret = cql_query(query, contact_points, port, cql_user, cql_pass) except CommandExecutionError: log.critical('Could not list users.') raise except BaseException as e: log.critical('Unexpected error while listing users: %s', e) raise return ret def create_user(username, password, superuser=False, contact_points=None, port=None, cql_user=None, cql_pass=None): ''' Create a new cassandra user with credentials and superuser status. :param username: The name of the new user. :type username: str :param password: The password of the new user. :type password: str :param superuser: Is the new user going to be a superuser? default: False :type superuser: bool :param contact_points: The Cassandra cluster addresses, can either be a string or a list of IPs. :type contact_points: str | list[str] :param cql_user: The Cassandra user if authentication is turned on. :type cql_user: str :param cql_pass: The Cassandra user password if authentication is turned on. :type cql_pass: str :param port: The Cassandra cluster port, defaults to None. :type port: int :return: :rtype: CLI Example: .. code-block:: bash salt 'minion1' cassandra_cql.create_user username=joe password=secret salt 'minion1' cassandra_cql.create_user username=joe password=secret superuser=True salt 'minion1' cassandra_cql.create_user username=joe password=secret superuser=True contact_points=minion1 ''' superuser_cql = 'superuser' if superuser else 'nosuperuser' query = '''create user if not exists {0} with password '{1}' {2};'''.format(username, password, superuser_cql) log.debug("Attempting to create a new user with username=%s superuser=%s", username, superuser_cql) # The create user query doesn't actually return anything if the query succeeds. # If the query fails, catch the exception, log a messange and raise it again. try: cql_query(query, contact_points, port, cql_user, cql_pass) except CommandExecutionError: log.critical('Could not create user.') raise except BaseException as e: log.critical('Unexpected error while creating user: %s', e) raise return True def create_role(username, password, superuser=False, login=False, contact_points=None, port=None, cql_user=None, cql_pass=None): ''' Create a new cassandra role with credentials and superuser status. :param username: The name of the new user. :type username: str :param password: The password of the new user. :type password: str :param superuser: Is the new role going to be a superuser? default: False :type superuser: bool :param login: Is the new role going to be allowed to log in? default: False :type superuser: bool :param contact_points: The Cassandra cluster addresses, can either be a string or a list of IPs. :type contact_points: str | list[str] :param cql_user: The Cassandra user if authentication is turned on. :type cql_user: str :param cql_pass: The Cassandra user password if authentication is turned on. :type cql_pass: str :param port: The Cassandra cluster port, defaults to None. :type port: int :return: :rtype: CLI Example: .. code-block:: bash salt 'minion1' cassandra_cql.create_role username=joe password=secret salt 'minion1' cassandra_cql.create_role username=joe password=secret superuser=True salt 'minion1' cassandra_cql.create_role username=joe password=secret superuser=True login=True salt 'minion1' cassandra_cql.create_role username=joe password=secret superuser=True login=True contact_points=minion1 ''' superuser_cql = 'superuser = true' if superuser else 'superuser = false' login_cql = 'login = true' if login else 'login = false' query = '''create role if not exists {0} with password '{1}' and {2} and {3} ;'''.format(username, password, superuser_cql, login_cql) log.debug("Attempting to create a new role with username=%s superuser=%s login=%s", username, superuser, login) # The create role query doesn't actually return anything if the query succeeds. # If the query fails, catch the exception, log a messange and raise it again. try: cql_query(query, contact_points, port, cql_user, cql_pass) except CommandExecutionError: log.critical('Could not create role.') raise except BaseException as e: log.critical('Unexpected error while creating role: %s', e) raise return True def list_permissions(username=None, resource=None, resource_type='keyspace', permission=None, contact_points=None, port=None, cql_user=None, cql_pass=None): ''' List permissions. :param username: The name of the user to list permissions for. :type username: str :param resource: The resource (keyspace or table), if None, permissions for all resources are listed. :type resource: str :param resource_type: The resource_type (keyspace or table), defaults to 'keyspace'. :type resource_type: str :param permission: A permission name (e.g. select), if None, all permissions are listed. :type permission: str :param contact_points: The Cassandra cluster addresses, can either be a string or a list of IPs. :type contact_points: str | list[str] :param cql_user: The Cassandra user if authentication is turned on. :type cql_user: str :param cql_pass: The Cassandra user password if authentication is turned on. :type cql_pass: str :param port: The Cassandra cluster port, defaults to None. :type port: int :return: Dictionary of permissions. :rtype: dict CLI Example: .. code-block:: bash salt 'minion1' cassandra_cql.list_permissions salt 'minion1' cassandra_cql.list_permissions username=joe resource=test_keyspace permission=select salt 'minion1' cassandra_cql.list_permissions username=joe resource=test_table resource_type=table \ permission=select contact_points=minion1 ''' keyspace_cql = "{0} {1}".format(resource_type, resource) if resource else "all keyspaces" permission_cql = "{0} permission".format(permission) if permission else "all permissions" query = "list {0} on {1}".format(permission_cql, keyspace_cql) if username: query = "{0} of {1}".format(query, username) log.debug("Attempting to list permissions with query '%s'", query) ret = {} try: ret = cql_query(query, contact_points, port, cql_user, cql_pass) except CommandExecutionError: log.critical('Could not list permissions.') raise except BaseException as e: log.critical('Unexpected error while listing permissions: %s', e) raise return ret def grant_permission(username, resource=None, resource_type='keyspace', permission=None, contact_points=None, port=None, cql_user=None, cql_pass=None): ''' Grant permissions to a user. :param username: The name of the user to grant permissions to. :type username: str :param resource: The resource (keyspace or table), if None, permissions for all resources are granted. :type resource: str :param resource_type: The resource_type (keyspace or table), defaults to 'keyspace'. :type resource_type: str :param permission: A permission name (e.g. select), if None, all permissions are granted. :type permission: str :param contact_points: The Cassandra cluster addresses, can either be a string or a list of IPs. :type contact_points: str | list[str] :param cql_user: The Cassandra user if authentication is turned on. :type cql_user: str :param cql_pass: The Cassandra user password if authentication is turned on. :type cql_pass: str :param port: The Cassandra cluster port, defaults to None. :type port: int :return: :rtype: CLI Example: .. code-block:: bash salt 'minion1' cassandra_cql.grant_permission salt 'minion1' cassandra_cql.grant_permission username=joe resource=test_keyspace permission=select salt 'minion1' cassandra_cql.grant_permission username=joe resource=test_table resource_type=table \ permission=select contact_points=minion1 ''' permission_cql = "grant {0}".format(permission) if permission else "grant all permissions" resource_cql = "on {0} {1}".format(resource_type, resource) if resource else "on all keyspaces" query = "{0} {1} to {2}".format(permission_cql, resource_cql, username) log.debug("Attempting to grant permissions with query '%s'", query) try: cql_query(query, contact_points, port, cql_user, cql_pass) except CommandExecutionError: log.critical('Could not grant permissions.') raise except BaseException as e: log.critical('Unexpected error while granting permissions: %s', e) raise return True
saltstack/salt
salt/modules/cassandra_cql.py
_connect
python
def _connect(contact_points=None, port=None, cql_user=None, cql_pass=None, protocol_version=None): ''' Connect to a Cassandra cluster. :param contact_points: The Cassandra cluster addresses, can either be a string or a list of IPs. :type contact_points: str or list of str :param cql_user: The Cassandra user if authentication is turned on. :type cql_user: str :param cql_pass: The Cassandra user password if authentication is turned on. :type cql_pass: str :param port: The Cassandra cluster port, defaults to None. :type port: int :param protocol_version: Cassandra protocol version to use. :type port: int :return: The session and cluster objects. :rtype: cluster object, session object ''' # Lazy load the Cassandra cluster and session for this module by creating a # cluster and session when cql_query is called the first time. Get the # Cassandra cluster and session from this module's __context__ after it is # loaded the first time cql_query is called. # # TODO: Call cluster.shutdown() when the module is unloaded on # master/minion shutdown. Currently, Master.shutdown() and Minion.shutdown() # do nothing to allow loaded modules to gracefully handle resources stored # in __context__ (i.e. connection pools). This means that the connection # pool is orphaned and Salt relies on Cassandra to reclaim connections. # Perhaps if Master/Minion daemons could be enhanced to call an "__unload__" # function, or something similar for each loaded module, connection pools # and the like can be gracefully reclaimed/shutdown. if (__context__ and 'cassandra_cql_returner_cluster' in __context__ and 'cassandra_cql_returner_session' in __context__): return __context__['cassandra_cql_returner_cluster'], __context__['cassandra_cql_returner_session'] else: contact_points = _load_properties(property_name=contact_points, config_option='cluster') contact_points = contact_points if isinstance(contact_points, list) else contact_points.split(',') port = _load_properties(property_name=port, config_option='port', set_default=True, default=9042) cql_user = _load_properties(property_name=cql_user, config_option='username', set_default=True, default="cassandra") cql_pass = _load_properties(property_name=cql_pass, config_option='password', set_default=True, default="cassandra") protocol_version = _load_properties(property_name=protocol_version, config_option='protocol_version', set_default=True, default=4) try: auth_provider = PlainTextAuthProvider(username=cql_user, password=cql_pass) ssl_opts = _get_ssl_opts() if ssl_opts: cluster = Cluster(contact_points, port=port, auth_provider=auth_provider, ssl_options=ssl_opts, protocol_version=protocol_version, compression=True) else: cluster = Cluster(contact_points, port=port, auth_provider=auth_provider, protocol_version=protocol_version, compression=True) for recontimes in range(1, 4): try: session = cluster.connect() break except OperationTimedOut: log.warning('Cassandra cluster.connect timed out, try %s', recontimes) if recontimes >= 3: raise # TODO: Call cluster.shutdown() when the module is unloaded on shutdown. __context__['cassandra_cql_returner_cluster'] = cluster __context__['cassandra_cql_returner_session'] = session __context__['cassandra_cql_prepared'] = {} log.debug('Successfully connected to Cassandra cluster at %s', contact_points) return cluster, session except TypeError: pass except (ConnectionException, ConnectionShutdown, NoHostAvailable): log.error('Could not connect to Cassandra cluster at %s', contact_points) raise CommandExecutionError('ERROR: Could not connect to Cassandra cluster.')
Connect to a Cassandra cluster. :param contact_points: The Cassandra cluster addresses, can either be a string or a list of IPs. :type contact_points: str or list of str :param cql_user: The Cassandra user if authentication is turned on. :type cql_user: str :param cql_pass: The Cassandra user password if authentication is turned on. :type cql_pass: str :param port: The Cassandra cluster port, defaults to None. :type port: int :param protocol_version: Cassandra protocol version to use. :type port: int :return: The session and cluster objects. :rtype: cluster object, session object
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/cassandra_cql.py#L201-L282
[ "def _load_properties(property_name, config_option, set_default=False, default=None):\n '''\n Load properties for the cassandra module from config or pillar.\n\n :param property_name: The property to load.\n :type property_name: str or list of str\n :param config_option: The name of the config option.\n :type config_option: str\n :param set_default: Should a default be set if not found in config.\n :type set_default: bool\n :param default: The default value to be set.\n :type default: str or int\n :return: The property fetched from the configuration or default.\n :rtype: str or list of str\n '''\n if not property_name:\n log.debug(\"No property specified in function, trying to load from salt configuration\")\n try:\n options = __salt__['config.option']('cassandra')\n except BaseException as e:\n log.error(\"Failed to get cassandra config options. Reason: %s\", e)\n raise\n\n loaded_property = options.get(config_option)\n if not loaded_property:\n if set_default:\n log.debug('Setting default Cassandra %s to %s', config_option, default)\n loaded_property = default\n else:\n log.error('No cassandra %s specified in the configuration or passed to the module.', config_option)\n raise CommandExecutionError(\"ERROR: Cassandra {0} cannot be empty.\".format(config_option))\n return loaded_property\n return property_name\n", "def _get_ssl_opts():\n '''\n Parse out ssl_options for Cassandra cluster connection.\n Make sure that the ssl_version (if any specified) is valid.\n '''\n sslopts = __salt__['config.option']('cassandra').get('ssl_options', None)\n ssl_opts = {}\n\n if sslopts:\n ssl_opts['ca_certs'] = sslopts['ca_certs']\n if SSL_VERSION in sslopts:\n if not sslopts[SSL_VERSION].startswith('PROTOCOL_'):\n valid_opts = ', '.join(\n [x for x in dir(ssl) if x.startswith('PROTOCOL_')]\n )\n raise CommandExecutionError('Invalid protocol_version '\n 'specified! '\n 'Please make sure '\n 'that the ssl protocol'\n 'version is one from the SSL'\n 'module. '\n 'Valid options are '\n '{0}'.format(valid_opts))\n else:\n ssl_opts[SSL_VERSION] = \\\n getattr(ssl, sslopts[SSL_VERSION])\n return ssl_opts\n else:\n return None\n" ]
# -*- coding: utf-8 -*- ''' Cassandra Database Module .. versionadded:: 2015.5.0 This module works with Cassandra v2 and v3 and hence generates queries based on the internal schema of said version. :depends: DataStax Python Driver for Apache Cassandra https://github.com/datastax/python-driver pip install cassandra-driver :referenced by: Salt's cassandra_cql returner :configuration: The Cassandra cluster members and connection port can either be specified in the master or minion config, the minion's pillar or be passed to the module. Example configuration in the config for a single node: .. code-block:: yaml cassandra: cluster: 192.168.50.10 port: 9000 Example configuration in the config for a cluster: .. code-block:: yaml cassandra: cluster: - 192.168.50.10 - 192.168.50.11 - 192.168.50.12 port: 9000 username: cas_admin .. versionchanged:: 2016.11.0 Added support for ``ssl_options`` and ``protocol_version``. Example configuration with `ssl options <http://datastax.github.io/python-driver/api/cassandra/cluster.html#cassandra.cluster.Cluster.ssl_options>`_: If ``ssl_options`` are present in cassandra config the cassandra_cql returner will use SSL. SSL isn't used if ``ssl_options`` isn't specified. .. code-block:: yaml cassandra: cluster: - 192.168.50.10 - 192.168.50.11 - 192.168.50.12 port: 9000 username: cas_admin ssl_options: ca_certs: /etc/ssl/certs/ca-bundle.trust.crt # SSL version should be one from the ssl module # This is an optional parameter ssl_version: PROTOCOL_TLSv1 Additionally you can also specify the ``protocol_version`` to `use <http://datastax.github.io/python-driver/api/cassandra/cluster.html#cassandra.cluster.Cluster.ssl_options>`_. .. code-block:: yaml cassandra: cluster: - 192.168.50.10 - 192.168.50.11 - 192.168.50.12 port: 9000 username: cas_admin # defaults to 4, if not set protocol_version: 3 ''' # Import Python Libs from __future__ import absolute_import, unicode_literals, print_function import logging import re import ssl # Import Salt Libs import salt.utils.json from salt.exceptions import CommandExecutionError # Import 3rd-party libs from salt.ext import six from salt.ext.six.moves import range import salt.utils.versions SSL_VERSION = 'ssl_version' log = logging.getLogger(__name__) __virtualname__ = 'cassandra_cql' HAS_DRIVER = False try: # pylint: disable=import-error,no-name-in-module from cassandra.cluster import Cluster from cassandra.cluster import NoHostAvailable from cassandra.connection import ConnectionException, \ ConnectionShutdown, OperationTimedOut from cassandra.auth import PlainTextAuthProvider from cassandra.query import dict_factory # pylint: enable=import-error,no-name-in-module HAS_DRIVER = True except ImportError: pass def __virtual__(): ''' Return virtual name of the module only if the python driver can be loaded. :return: The virtual name of the module. :rtype: str ''' if HAS_DRIVER: return __virtualname__ return (False, 'Cannot load cassandra_cql module: python driver not found') def _async_log_errors(errors): log.error('Cassandra_cql asynchronous call returned: %s', errors) def _load_properties(property_name, config_option, set_default=False, default=None): ''' Load properties for the cassandra module from config or pillar. :param property_name: The property to load. :type property_name: str or list of str :param config_option: The name of the config option. :type config_option: str :param set_default: Should a default be set if not found in config. :type set_default: bool :param default: The default value to be set. :type default: str or int :return: The property fetched from the configuration or default. :rtype: str or list of str ''' if not property_name: log.debug("No property specified in function, trying to load from salt configuration") try: options = __salt__['config.option']('cassandra') except BaseException as e: log.error("Failed to get cassandra config options. Reason: %s", e) raise loaded_property = options.get(config_option) if not loaded_property: if set_default: log.debug('Setting default Cassandra %s to %s', config_option, default) loaded_property = default else: log.error('No cassandra %s specified in the configuration or passed to the module.', config_option) raise CommandExecutionError("ERROR: Cassandra {0} cannot be empty.".format(config_option)) return loaded_property return property_name def _get_ssl_opts(): ''' Parse out ssl_options for Cassandra cluster connection. Make sure that the ssl_version (if any specified) is valid. ''' sslopts = __salt__['config.option']('cassandra').get('ssl_options', None) ssl_opts = {} if sslopts: ssl_opts['ca_certs'] = sslopts['ca_certs'] if SSL_VERSION in sslopts: if not sslopts[SSL_VERSION].startswith('PROTOCOL_'): valid_opts = ', '.join( [x for x in dir(ssl) if x.startswith('PROTOCOL_')] ) raise CommandExecutionError('Invalid protocol_version ' 'specified! ' 'Please make sure ' 'that the ssl protocol' 'version is one from the SSL' 'module. ' 'Valid options are ' '{0}'.format(valid_opts)) else: ssl_opts[SSL_VERSION] = \ getattr(ssl, sslopts[SSL_VERSION]) return ssl_opts else: return None def cql_query(query, contact_points=None, port=None, cql_user=None, cql_pass=None): ''' Run a query on a Cassandra cluster and return a dictionary. :param query: The query to execute. :type query: str :param contact_points: The Cassandra cluster addresses, can either be a string or a list of IPs. :type contact_points: str | list[str] :param cql_user: The Cassandra user if authentication is turned on. :type cql_user: str :param cql_pass: The Cassandra user password if authentication is turned on. :type cql_pass: str :param port: The Cassandra cluster port, defaults to None. :type port: int :param params: The parameters for the query, optional. :type params: str :return: A dictionary from the return values of the query :rtype: list[dict] CLI Example: .. code-block:: bash salt 'cassandra-server' cassandra_cql.cql_query "SELECT * FROM users_by_name WHERE first_name = 'jane'" ''' try: cluster, session = _connect(contact_points=contact_points, port=port, cql_user=cql_user, cql_pass=cql_pass) except CommandExecutionError: log.critical('Could not get Cassandra cluster session.') raise except BaseException as e: log.critical('Unexpected error while getting Cassandra cluster session: %s', e) raise session.row_factory = dict_factory ret = [] # Cassandra changed their internal schema from v2 to v3 # If the query contains a dictionary sorted by versions # Find the query for the current cluster version. # https://issues.apache.org/jira/browse/CASSANDRA-6717 if isinstance(query, dict): cluster_version = version(contact_points=contact_points, port=port, cql_user=cql_user, cql_pass=cql_pass) match = re.match(r'^(\d+)\.(\d+)(?:\.(\d+))?', cluster_version) major, minor, point = match.groups() # try to find the specific version in the query dictionary # then try the major version # otherwise default to the highest version number try: query = query[cluster_version] except KeyError: query = query.get(major, max(query)) log.debug('New query is: %s', query) try: results = session.execute(query) except BaseException as e: log.error('Failed to execute query: %s\n reason: %s', query, e) msg = "ERROR: Cassandra query failed: {0} reason: {1}".format(query, e) raise CommandExecutionError(msg) if results: for result in results: values = {} for key, value in six.iteritems(result): # Salt won't return dictionaries with odd types like uuid.UUID if not isinstance(value, six.text_type): # Must support Cassandra collection types. # Namely, Cassandras set, list, and map collections. if not isinstance(value, (set, list, dict)): value = six.text_type(value) values[key] = value ret.append(values) return ret def cql_query_with_prepare(query, statement_name, statement_arguments, callback_errors=None, contact_points=None, port=None, cql_user=None, cql_pass=None, **kwargs): ''' Run a query on a Cassandra cluster and return a dictionary. This function should not be used asynchronously for SELECTs -- it will not return anything and we don't currently have a mechanism for handling a future that will return results. :param query: The query to execute. :type query: str :param statement_name: Name to assign the prepared statement in the __context__ dictionary :type statement_name: str :param statement_arguments: Bind parameters for the SQL statement :type statement_arguments: list[str] :param async: Run this query in asynchronous mode :type async: bool :param callback_errors: Function to call after query runs if there is an error :type callback_errors: Function callable :param contact_points: The Cassandra cluster addresses, can either be a string or a list of IPs. :type contact_points: str | list[str] :param cql_user: The Cassandra user if authentication is turned on. :type cql_user: str :param cql_pass: The Cassandra user password if authentication is turned on. :type cql_pass: str :param port: The Cassandra cluster port, defaults to None. :type port: int :param params: The parameters for the query, optional. :type params: str :return: A dictionary from the return values of the query :rtype: list[dict] CLI Example: .. code-block:: bash # Insert data asynchronously salt this-node cassandra_cql.cql_query_with_prepare "name_insert" "INSERT INTO USERS (first_name, last_name) VALUES (?, ?)" \ statement_arguments=['John','Doe'], asynchronous=True # Select data, should not be asynchronous because there is not currently a facility to return data from a future salt this-node cassandra_cql.cql_query_with_prepare "name_select" "SELECT * FROM USERS WHERE first_name=?" \ statement_arguments=['John'] ''' # Backward-compatibility with Python 3.7: "async" is a reserved word asynchronous = kwargs.get('async', False) try: cluster, session = _connect(contact_points=contact_points, port=port, cql_user=cql_user, cql_pass=cql_pass) except CommandExecutionError: log.critical('Could not get Cassandra cluster session.') raise except BaseException as e: log.critical('Unexpected error while getting Cassandra cluster session: %s', e) raise if statement_name not in __context__['cassandra_cql_prepared']: try: bound_statement = session.prepare(query) __context__['cassandra_cql_prepared'][statement_name] = bound_statement except BaseException as e: log.critical('Unexpected error while preparing SQL statement: %s', e) raise else: bound_statement = __context__['cassandra_cql_prepared'][statement_name] session.row_factory = dict_factory ret = [] try: if asynchronous: future_results = session.execute_async(bound_statement.bind(statement_arguments)) # future_results.add_callbacks(_async_log_errors) else: results = session.execute(bound_statement.bind(statement_arguments)) except BaseException as e: log.error('Failed to execute query: %s\n reason: %s', query, e) msg = "ERROR: Cassandra query failed: {0} reason: {1}".format(query, e) raise CommandExecutionError(msg) if not asynchronous and results: for result in results: values = {} for key, value in six.iteritems(result): # Salt won't return dictionaries with odd types like uuid.UUID if not isinstance(value, six.text_type): # Must support Cassandra collection types. # Namely, Cassandras set, list, and map collections. if not isinstance(value, (set, list, dict)): value = six.text_type(value) values[key] = value ret.append(values) # If this was a synchronous call, then we either have an empty list # because there was no return, or we have a return # If this was an asynchronous call we only return the empty list return ret def version(contact_points=None, port=None, cql_user=None, cql_pass=None): ''' Show the Cassandra version. :param contact_points: The Cassandra cluster addresses, can either be a string or a list of IPs. :type contact_points: str | list[str] :param cql_user: The Cassandra user if authentication is turned on. :type cql_user: str :param cql_pass: The Cassandra user password if authentication is turned on. :type cql_pass: str :param port: The Cassandra cluster port, defaults to None. :type port: int :return: The version for this Cassandra cluster. :rtype: str CLI Example: .. code-block:: bash salt 'minion1' cassandra_cql.version salt 'minion1' cassandra_cql.version contact_points=minion1 ''' query = '''select release_version from system.local limit 1;''' try: ret = cql_query(query, contact_points, port, cql_user, cql_pass) except CommandExecutionError: log.critical('Could not get Cassandra version.') raise except BaseException as e: log.critical('Unexpected error while getting Cassandra version: %s', e) raise return ret[0].get('release_version') def info(contact_points=None, port=None, cql_user=None, cql_pass=None): ''' Show the Cassandra information for this cluster. :param contact_points: The Cassandra cluster addresses, can either be a string or a list of IPs. :type contact_points: str | list[str] :param cql_user: The Cassandra user if authentication is turned on. :type cql_user: str :param cql_pass: The Cassandra user password if authentication is turned on. :type cql_pass: str :param port: The Cassandra cluster port, defaults to None. :type port: int :return: The information for this Cassandra cluster. :rtype: dict CLI Example: .. code-block:: bash salt 'minion1' cassandra_cql.info salt 'minion1' cassandra_cql.info contact_points=minion1 ''' query = '''select cluster_name, data_center, partitioner, host_id, rack, release_version, cql_version, schema_version, thrift_version from system.local limit 1;''' ret = {} try: ret = cql_query(query, contact_points, port, cql_user, cql_pass) except CommandExecutionError: log.critical('Could not list Cassandra info.') raise except BaseException as e: log.critical('Unexpected error while listing Cassandra info: %s', e) raise return ret def list_keyspaces(contact_points=None, port=None, cql_user=None, cql_pass=None): ''' List keyspaces in a Cassandra cluster. :param contact_points: The Cassandra cluster addresses, can either be a string or a list of IPs. :type contact_points: str | list[str] :param cql_user: The Cassandra user if authentication is turned on. :type cql_user: str :param cql_pass: The Cassandra user password if authentication is turned on. :type cql_pass: str :param port: The Cassandra cluster port, defaults to None. :type port: int :return: The keyspaces in this Cassandra cluster. :rtype: list[dict] CLI Example: .. code-block:: bash salt 'minion1' cassandra_cql.list_keyspaces salt 'minion1' cassandra_cql.list_keyspaces contact_points=minion1 port=9000 ''' query = { '2': 'select keyspace_name from system.schema_keyspaces;', '3': 'select keyspace_name from system_schema.keyspaces;', } ret = {} try: ret = cql_query(query, contact_points, port, cql_user, cql_pass) except CommandExecutionError: log.critical('Could not list keyspaces.') raise except BaseException as e: log.critical('Unexpected error while listing keyspaces: %s', e) raise return ret def list_column_families(keyspace=None, contact_points=None, port=None, cql_user=None, cql_pass=None): ''' List column families in a Cassandra cluster for all keyspaces or just the provided one. :param keyspace: The keyspace to provide the column families for, optional. :type keyspace: str :param contact_points: The Cassandra cluster addresses, can either be a string or a list of IPs. :type contact_points: str | list[str] :param cql_user: The Cassandra user if authentication is turned on. :type cql_user: str :param cql_pass: The Cassandra user password if authentication is turned on. :type cql_pass: str :param port: The Cassandra cluster port, defaults to None. :type port: int :return: The column families in this Cassandra cluster. :rtype: list[dict] CLI Example: .. code-block:: bash salt 'minion1' cassandra_cql.list_column_families salt 'minion1' cassandra_cql.list_column_families contact_points=minion1 salt 'minion1' cassandra_cql.list_column_families keyspace=system ''' where_clause = "where keyspace_name = '{0}'".format(keyspace) if keyspace else "" query = { '2': '''select columnfamily_name from system.schema_columnfamilies {0};'''.format(where_clause), '3': '''select column_name from system_schema.columns {0};'''.format(where_clause), } ret = {} try: ret = cql_query(query, contact_points, port, cql_user, cql_pass) except CommandExecutionError: log.critical('Could not list column families.') raise except BaseException as e: log.critical('Unexpected error while listing column families: %s', e) raise return ret def keyspace_exists(keyspace, contact_points=None, port=None, cql_user=None, cql_pass=None): ''' Check if a keyspace exists in a Cassandra cluster. :param keyspace The keyspace name to check for. :type keyspace: str :param contact_points: The Cassandra cluster addresses, can either be a string or a list of IPs. :type contact_points: str | list[str] :param cql_user: The Cassandra user if authentication is turned on. :type cql_user: str :param cql_pass: The Cassandra user password if authentication is turned on. :type cql_pass: str :param port: The Cassandra cluster port, defaults to None. :type port: int :return: The info for the keyspace or False if it does not exist. :rtype: dict CLI Example: .. code-block:: bash salt 'minion1' cassandra_cql.keyspace_exists keyspace=system ''' query = { '2': '''select keyspace_name from system.schema_keyspaces where keyspace_name = '{0}';'''.format(keyspace), '3': '''select keyspace_name from system_schema.keyspaces where keyspace_name = '{0}';'''.format(keyspace), } try: ret = cql_query(query, contact_points, port, cql_user, cql_pass) except CommandExecutionError: log.critical('Could not determine if keyspace exists.') raise except BaseException as e: log.critical('Unexpected error while determining if keyspace exists: %s', e) raise return True if ret else False def create_keyspace(keyspace, replication_strategy='SimpleStrategy', replication_factor=1, replication_datacenters=None, contact_points=None, port=None, cql_user=None, cql_pass=None): ''' Create a new keyspace in Cassandra. :param keyspace: The keyspace name :type keyspace: str :param replication_strategy: either `SimpleStrategy` or `NetworkTopologyStrategy` :type replication_strategy: str :param replication_factor: number of replicas of data on multiple nodes. not used if using NetworkTopologyStrategy :type replication_factor: int :param replication_datacenters: string or dict of datacenter names to replication factors, required if using NetworkTopologyStrategy (will be a dict if coming from state file). :type replication_datacenters: str | dict[str, int] :param contact_points: The Cassandra cluster addresses, can either be a string or a list of IPs. :type contact_points: str | list[str] :param cql_user: The Cassandra user if authentication is turned on. :type cql_user: str :param cql_pass: The Cassandra user password if authentication is turned on. :type cql_pass: str :param port: The Cassandra cluster port, defaults to None. :type port: int :return: The info for the keyspace or False if it does not exist. :rtype: dict CLI Example: .. code-block:: bash # CLI Example: salt 'minion1' cassandra_cql.create_keyspace keyspace=newkeyspace salt 'minion1' cassandra_cql.create_keyspace keyspace=newkeyspace replication_strategy=NetworkTopologyStrategy \ replication_datacenters='{"datacenter_1": 3, "datacenter_2": 2}' ''' existing_keyspace = keyspace_exists(keyspace, contact_points, port) if not existing_keyspace: # Add the strategy, replication_factor, etc. replication_map = { 'class': replication_strategy } if replication_datacenters: if isinstance(replication_datacenters, six.string_types): try: replication_datacenter_map = salt.utils.json.loads(replication_datacenters) replication_map.update(**replication_datacenter_map) except BaseException: # pylint: disable=W0703 log.error("Could not load json replication_datacenters.") return False else: replication_map.update(**replication_datacenters) else: replication_map['replication_factor'] = replication_factor query = '''create keyspace {0} with replication = {1} and durable_writes = true;'''.format(keyspace, replication_map) try: cql_query(query, contact_points, port, cql_user, cql_pass) except CommandExecutionError: log.critical('Could not create keyspace.') raise except BaseException as e: log.critical('Unexpected error while creating keyspace: %s', e) raise def drop_keyspace(keyspace, contact_points=None, port=None, cql_user=None, cql_pass=None): ''' Drop a keyspace if it exists in a Cassandra cluster. :param keyspace: The keyspace to drop. :type keyspace: str :param contact_points: The Cassandra cluster addresses, can either be a string or a list of IPs. :type contact_points: str | list[str] :param cql_user: The Cassandra user if authentication is turned on. :type cql_user: str :param cql_pass: The Cassandra user password if authentication is turned on. :type cql_pass: str :param port: The Cassandra cluster port, defaults to None. :type port: int :return: The info for the keyspace or False if it does not exist. :rtype: dict CLI Example: .. code-block:: bash salt 'minion1' cassandra_cql.drop_keyspace keyspace=test salt 'minion1' cassandra_cql.drop_keyspace keyspace=test contact_points=minion1 ''' existing_keyspace = keyspace_exists(keyspace, contact_points, port) if existing_keyspace: query = '''drop keyspace {0};'''.format(keyspace) try: cql_query(query, contact_points, port, cql_user, cql_pass) except CommandExecutionError: log.critical('Could not drop keyspace.') raise except BaseException as e: log.critical('Unexpected error while dropping keyspace: %s', e) raise return True def list_users(contact_points=None, port=None, cql_user=None, cql_pass=None): ''' List existing users in this Cassandra cluster. :param contact_points: The Cassandra cluster addresses, can either be a string or a list of IPs. :type contact_points: str | list[str] :param port: The Cassandra cluster port, defaults to None. :type port: int :param cql_user: The Cassandra user if authentication is turned on. :type cql_user: str :param cql_pass: The Cassandra user password if authentication is turned on. :type cql_pass: str :return: The list of existing users. :rtype: dict CLI Example: .. code-block:: bash salt 'minion1' cassandra_cql.list_users salt 'minion1' cassandra_cql.list_users contact_points=minion1 ''' query = "list users;" ret = {} try: ret = cql_query(query, contact_points, port, cql_user, cql_pass) except CommandExecutionError: log.critical('Could not list users.') raise except BaseException as e: log.critical('Unexpected error while listing users: %s', e) raise return ret def create_user(username, password, superuser=False, contact_points=None, port=None, cql_user=None, cql_pass=None): ''' Create a new cassandra user with credentials and superuser status. :param username: The name of the new user. :type username: str :param password: The password of the new user. :type password: str :param superuser: Is the new user going to be a superuser? default: False :type superuser: bool :param contact_points: The Cassandra cluster addresses, can either be a string or a list of IPs. :type contact_points: str | list[str] :param cql_user: The Cassandra user if authentication is turned on. :type cql_user: str :param cql_pass: The Cassandra user password if authentication is turned on. :type cql_pass: str :param port: The Cassandra cluster port, defaults to None. :type port: int :return: :rtype: CLI Example: .. code-block:: bash salt 'minion1' cassandra_cql.create_user username=joe password=secret salt 'minion1' cassandra_cql.create_user username=joe password=secret superuser=True salt 'minion1' cassandra_cql.create_user username=joe password=secret superuser=True contact_points=minion1 ''' superuser_cql = 'superuser' if superuser else 'nosuperuser' query = '''create user if not exists {0} with password '{1}' {2};'''.format(username, password, superuser_cql) log.debug("Attempting to create a new user with username=%s superuser=%s", username, superuser_cql) # The create user query doesn't actually return anything if the query succeeds. # If the query fails, catch the exception, log a messange and raise it again. try: cql_query(query, contact_points, port, cql_user, cql_pass) except CommandExecutionError: log.critical('Could not create user.') raise except BaseException as e: log.critical('Unexpected error while creating user: %s', e) raise return True def create_role(username, password, superuser=False, login=False, contact_points=None, port=None, cql_user=None, cql_pass=None): ''' Create a new cassandra role with credentials and superuser status. :param username: The name of the new user. :type username: str :param password: The password of the new user. :type password: str :param superuser: Is the new role going to be a superuser? default: False :type superuser: bool :param login: Is the new role going to be allowed to log in? default: False :type superuser: bool :param contact_points: The Cassandra cluster addresses, can either be a string or a list of IPs. :type contact_points: str | list[str] :param cql_user: The Cassandra user if authentication is turned on. :type cql_user: str :param cql_pass: The Cassandra user password if authentication is turned on. :type cql_pass: str :param port: The Cassandra cluster port, defaults to None. :type port: int :return: :rtype: CLI Example: .. code-block:: bash salt 'minion1' cassandra_cql.create_role username=joe password=secret salt 'minion1' cassandra_cql.create_role username=joe password=secret superuser=True salt 'minion1' cassandra_cql.create_role username=joe password=secret superuser=True login=True salt 'minion1' cassandra_cql.create_role username=joe password=secret superuser=True login=True contact_points=minion1 ''' superuser_cql = 'superuser = true' if superuser else 'superuser = false' login_cql = 'login = true' if login else 'login = false' query = '''create role if not exists {0} with password '{1}' and {2} and {3} ;'''.format(username, password, superuser_cql, login_cql) log.debug("Attempting to create a new role with username=%s superuser=%s login=%s", username, superuser, login) # The create role query doesn't actually return anything if the query succeeds. # If the query fails, catch the exception, log a messange and raise it again. try: cql_query(query, contact_points, port, cql_user, cql_pass) except CommandExecutionError: log.critical('Could not create role.') raise except BaseException as e: log.critical('Unexpected error while creating role: %s', e) raise return True def list_permissions(username=None, resource=None, resource_type='keyspace', permission=None, contact_points=None, port=None, cql_user=None, cql_pass=None): ''' List permissions. :param username: The name of the user to list permissions for. :type username: str :param resource: The resource (keyspace or table), if None, permissions for all resources are listed. :type resource: str :param resource_type: The resource_type (keyspace or table), defaults to 'keyspace'. :type resource_type: str :param permission: A permission name (e.g. select), if None, all permissions are listed. :type permission: str :param contact_points: The Cassandra cluster addresses, can either be a string or a list of IPs. :type contact_points: str | list[str] :param cql_user: The Cassandra user if authentication is turned on. :type cql_user: str :param cql_pass: The Cassandra user password if authentication is turned on. :type cql_pass: str :param port: The Cassandra cluster port, defaults to None. :type port: int :return: Dictionary of permissions. :rtype: dict CLI Example: .. code-block:: bash salt 'minion1' cassandra_cql.list_permissions salt 'minion1' cassandra_cql.list_permissions username=joe resource=test_keyspace permission=select salt 'minion1' cassandra_cql.list_permissions username=joe resource=test_table resource_type=table \ permission=select contact_points=minion1 ''' keyspace_cql = "{0} {1}".format(resource_type, resource) if resource else "all keyspaces" permission_cql = "{0} permission".format(permission) if permission else "all permissions" query = "list {0} on {1}".format(permission_cql, keyspace_cql) if username: query = "{0} of {1}".format(query, username) log.debug("Attempting to list permissions with query '%s'", query) ret = {} try: ret = cql_query(query, contact_points, port, cql_user, cql_pass) except CommandExecutionError: log.critical('Could not list permissions.') raise except BaseException as e: log.critical('Unexpected error while listing permissions: %s', e) raise return ret def grant_permission(username, resource=None, resource_type='keyspace', permission=None, contact_points=None, port=None, cql_user=None, cql_pass=None): ''' Grant permissions to a user. :param username: The name of the user to grant permissions to. :type username: str :param resource: The resource (keyspace or table), if None, permissions for all resources are granted. :type resource: str :param resource_type: The resource_type (keyspace or table), defaults to 'keyspace'. :type resource_type: str :param permission: A permission name (e.g. select), if None, all permissions are granted. :type permission: str :param contact_points: The Cassandra cluster addresses, can either be a string or a list of IPs. :type contact_points: str | list[str] :param cql_user: The Cassandra user if authentication is turned on. :type cql_user: str :param cql_pass: The Cassandra user password if authentication is turned on. :type cql_pass: str :param port: The Cassandra cluster port, defaults to None. :type port: int :return: :rtype: CLI Example: .. code-block:: bash salt 'minion1' cassandra_cql.grant_permission salt 'minion1' cassandra_cql.grant_permission username=joe resource=test_keyspace permission=select salt 'minion1' cassandra_cql.grant_permission username=joe resource=test_table resource_type=table \ permission=select contact_points=minion1 ''' permission_cql = "grant {0}".format(permission) if permission else "grant all permissions" resource_cql = "on {0} {1}".format(resource_type, resource) if resource else "on all keyspaces" query = "{0} {1} to {2}".format(permission_cql, resource_cql, username) log.debug("Attempting to grant permissions with query '%s'", query) try: cql_query(query, contact_points, port, cql_user, cql_pass) except CommandExecutionError: log.critical('Could not grant permissions.') raise except BaseException as e: log.critical('Unexpected error while granting permissions: %s', e) raise return True
saltstack/salt
salt/modules/cassandra_cql.py
cql_query
python
def cql_query(query, contact_points=None, port=None, cql_user=None, cql_pass=None): ''' Run a query on a Cassandra cluster and return a dictionary. :param query: The query to execute. :type query: str :param contact_points: The Cassandra cluster addresses, can either be a string or a list of IPs. :type contact_points: str | list[str] :param cql_user: The Cassandra user if authentication is turned on. :type cql_user: str :param cql_pass: The Cassandra user password if authentication is turned on. :type cql_pass: str :param port: The Cassandra cluster port, defaults to None. :type port: int :param params: The parameters for the query, optional. :type params: str :return: A dictionary from the return values of the query :rtype: list[dict] CLI Example: .. code-block:: bash salt 'cassandra-server' cassandra_cql.cql_query "SELECT * FROM users_by_name WHERE first_name = 'jane'" ''' try: cluster, session = _connect(contact_points=contact_points, port=port, cql_user=cql_user, cql_pass=cql_pass) except CommandExecutionError: log.critical('Could not get Cassandra cluster session.') raise except BaseException as e: log.critical('Unexpected error while getting Cassandra cluster session: %s', e) raise session.row_factory = dict_factory ret = [] # Cassandra changed their internal schema from v2 to v3 # If the query contains a dictionary sorted by versions # Find the query for the current cluster version. # https://issues.apache.org/jira/browse/CASSANDRA-6717 if isinstance(query, dict): cluster_version = version(contact_points=contact_points, port=port, cql_user=cql_user, cql_pass=cql_pass) match = re.match(r'^(\d+)\.(\d+)(?:\.(\d+))?', cluster_version) major, minor, point = match.groups() # try to find the specific version in the query dictionary # then try the major version # otherwise default to the highest version number try: query = query[cluster_version] except KeyError: query = query.get(major, max(query)) log.debug('New query is: %s', query) try: results = session.execute(query) except BaseException as e: log.error('Failed to execute query: %s\n reason: %s', query, e) msg = "ERROR: Cassandra query failed: {0} reason: {1}".format(query, e) raise CommandExecutionError(msg) if results: for result in results: values = {} for key, value in six.iteritems(result): # Salt won't return dictionaries with odd types like uuid.UUID if not isinstance(value, six.text_type): # Must support Cassandra collection types. # Namely, Cassandras set, list, and map collections. if not isinstance(value, (set, list, dict)): value = six.text_type(value) values[key] = value ret.append(values) return ret
Run a query on a Cassandra cluster and return a dictionary. :param query: The query to execute. :type query: str :param contact_points: The Cassandra cluster addresses, can either be a string or a list of IPs. :type contact_points: str | list[str] :param cql_user: The Cassandra user if authentication is turned on. :type cql_user: str :param cql_pass: The Cassandra user password if authentication is turned on. :type cql_pass: str :param port: The Cassandra cluster port, defaults to None. :type port: int :param params: The parameters for the query, optional. :type params: str :return: A dictionary from the return values of the query :rtype: list[dict] CLI Example: .. code-block:: bash salt 'cassandra-server' cassandra_cql.cql_query "SELECT * FROM users_by_name WHERE first_name = 'jane'"
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/cassandra_cql.py#L285-L362
[ "def iteritems(d, **kw):\n return d.iteritems(**kw)\n", "def version(contact_points=None, port=None, cql_user=None, cql_pass=None):\n '''\n Show the Cassandra version.\n\n :param contact_points: The Cassandra cluster addresses, can either be a string or a list of IPs.\n :type contact_points: str | list[str]\n :param cql_user: The Cassandra user if authentication is turned on.\n :type cql_user: str\n :param cql_pass: The Cassandra user password if authentication is turned on.\n :type cql_pass: str\n :param port: The Cassandra cluster port, defaults to None.\n :type port: int\n :return: The version for this Cassandra cluster.\n :rtype: str\n\n CLI Example:\n\n .. code-block:: bash\n\n salt 'minion1' cassandra_cql.version\n\n salt 'minion1' cassandra_cql.version contact_points=minion1\n '''\n query = '''select release_version\n from system.local\n limit 1;'''\n\n try:\n ret = cql_query(query, contact_points, port, cql_user, cql_pass)\n except CommandExecutionError:\n log.critical('Could not get Cassandra version.')\n raise\n except BaseException as e:\n log.critical('Unexpected error while getting Cassandra version: %s', e)\n raise\n\n return ret[0].get('release_version')\n", "def _connect(contact_points=None, port=None, cql_user=None, cql_pass=None,\n protocol_version=None):\n '''\n Connect to a Cassandra cluster.\n\n :param contact_points: The Cassandra cluster addresses, can either be a string or a list of IPs.\n :type contact_points: str or list of str\n :param cql_user: The Cassandra user if authentication is turned on.\n :type cql_user: str\n :param cql_pass: The Cassandra user password if authentication is turned on.\n :type cql_pass: str\n :param port: The Cassandra cluster port, defaults to None.\n :type port: int\n :param protocol_version: Cassandra protocol version to use.\n :type port: int\n :return: The session and cluster objects.\n :rtype: cluster object, session object\n '''\n # Lazy load the Cassandra cluster and session for this module by creating a\n # cluster and session when cql_query is called the first time. Get the\n # Cassandra cluster and session from this module's __context__ after it is\n # loaded the first time cql_query is called.\n #\n # TODO: Call cluster.shutdown() when the module is unloaded on\n # master/minion shutdown. Currently, Master.shutdown() and Minion.shutdown()\n # do nothing to allow loaded modules to gracefully handle resources stored\n # in __context__ (i.e. connection pools). This means that the connection\n # pool is orphaned and Salt relies on Cassandra to reclaim connections.\n # Perhaps if Master/Minion daemons could be enhanced to call an \"__unload__\"\n # function, or something similar for each loaded module, connection pools\n # and the like can be gracefully reclaimed/shutdown.\n if (__context__\n and 'cassandra_cql_returner_cluster' in __context__\n and 'cassandra_cql_returner_session' in __context__):\n return __context__['cassandra_cql_returner_cluster'], __context__['cassandra_cql_returner_session']\n else:\n\n contact_points = _load_properties(property_name=contact_points, config_option='cluster')\n contact_points = contact_points if isinstance(contact_points, list) else contact_points.split(',')\n port = _load_properties(property_name=port, config_option='port', set_default=True, default=9042)\n cql_user = _load_properties(property_name=cql_user, config_option='username', set_default=True, default=\"cassandra\")\n cql_pass = _load_properties(property_name=cql_pass, config_option='password', set_default=True, default=\"cassandra\")\n protocol_version = _load_properties(property_name=protocol_version,\n config_option='protocol_version',\n set_default=True, default=4)\n\n try:\n auth_provider = PlainTextAuthProvider(username=cql_user, password=cql_pass)\n ssl_opts = _get_ssl_opts()\n if ssl_opts:\n cluster = Cluster(contact_points,\n port=port,\n auth_provider=auth_provider,\n ssl_options=ssl_opts,\n protocol_version=protocol_version,\n compression=True)\n else:\n cluster = Cluster(contact_points, port=port,\n auth_provider=auth_provider,\n protocol_version=protocol_version,\n compression=True)\n for recontimes in range(1, 4):\n try:\n session = cluster.connect()\n break\n except OperationTimedOut:\n log.warning('Cassandra cluster.connect timed out, try %s', recontimes)\n if recontimes >= 3:\n raise\n\n # TODO: Call cluster.shutdown() when the module is unloaded on shutdown.\n __context__['cassandra_cql_returner_cluster'] = cluster\n __context__['cassandra_cql_returner_session'] = session\n __context__['cassandra_cql_prepared'] = {}\n\n log.debug('Successfully connected to Cassandra cluster at %s', contact_points)\n return cluster, session\n except TypeError:\n pass\n except (ConnectionException, ConnectionShutdown, NoHostAvailable):\n log.error('Could not connect to Cassandra cluster at %s', contact_points)\n raise CommandExecutionError('ERROR: Could not connect to Cassandra cluster.')\n" ]
# -*- coding: utf-8 -*- ''' Cassandra Database Module .. versionadded:: 2015.5.0 This module works with Cassandra v2 and v3 and hence generates queries based on the internal schema of said version. :depends: DataStax Python Driver for Apache Cassandra https://github.com/datastax/python-driver pip install cassandra-driver :referenced by: Salt's cassandra_cql returner :configuration: The Cassandra cluster members and connection port can either be specified in the master or minion config, the minion's pillar or be passed to the module. Example configuration in the config for a single node: .. code-block:: yaml cassandra: cluster: 192.168.50.10 port: 9000 Example configuration in the config for a cluster: .. code-block:: yaml cassandra: cluster: - 192.168.50.10 - 192.168.50.11 - 192.168.50.12 port: 9000 username: cas_admin .. versionchanged:: 2016.11.0 Added support for ``ssl_options`` and ``protocol_version``. Example configuration with `ssl options <http://datastax.github.io/python-driver/api/cassandra/cluster.html#cassandra.cluster.Cluster.ssl_options>`_: If ``ssl_options`` are present in cassandra config the cassandra_cql returner will use SSL. SSL isn't used if ``ssl_options`` isn't specified. .. code-block:: yaml cassandra: cluster: - 192.168.50.10 - 192.168.50.11 - 192.168.50.12 port: 9000 username: cas_admin ssl_options: ca_certs: /etc/ssl/certs/ca-bundle.trust.crt # SSL version should be one from the ssl module # This is an optional parameter ssl_version: PROTOCOL_TLSv1 Additionally you can also specify the ``protocol_version`` to `use <http://datastax.github.io/python-driver/api/cassandra/cluster.html#cassandra.cluster.Cluster.ssl_options>`_. .. code-block:: yaml cassandra: cluster: - 192.168.50.10 - 192.168.50.11 - 192.168.50.12 port: 9000 username: cas_admin # defaults to 4, if not set protocol_version: 3 ''' # Import Python Libs from __future__ import absolute_import, unicode_literals, print_function import logging import re import ssl # Import Salt Libs import salt.utils.json from salt.exceptions import CommandExecutionError # Import 3rd-party libs from salt.ext import six from salt.ext.six.moves import range import salt.utils.versions SSL_VERSION = 'ssl_version' log = logging.getLogger(__name__) __virtualname__ = 'cassandra_cql' HAS_DRIVER = False try: # pylint: disable=import-error,no-name-in-module from cassandra.cluster import Cluster from cassandra.cluster import NoHostAvailable from cassandra.connection import ConnectionException, \ ConnectionShutdown, OperationTimedOut from cassandra.auth import PlainTextAuthProvider from cassandra.query import dict_factory # pylint: enable=import-error,no-name-in-module HAS_DRIVER = True except ImportError: pass def __virtual__(): ''' Return virtual name of the module only if the python driver can be loaded. :return: The virtual name of the module. :rtype: str ''' if HAS_DRIVER: return __virtualname__ return (False, 'Cannot load cassandra_cql module: python driver not found') def _async_log_errors(errors): log.error('Cassandra_cql asynchronous call returned: %s', errors) def _load_properties(property_name, config_option, set_default=False, default=None): ''' Load properties for the cassandra module from config or pillar. :param property_name: The property to load. :type property_name: str or list of str :param config_option: The name of the config option. :type config_option: str :param set_default: Should a default be set if not found in config. :type set_default: bool :param default: The default value to be set. :type default: str or int :return: The property fetched from the configuration or default. :rtype: str or list of str ''' if not property_name: log.debug("No property specified in function, trying to load from salt configuration") try: options = __salt__['config.option']('cassandra') except BaseException as e: log.error("Failed to get cassandra config options. Reason: %s", e) raise loaded_property = options.get(config_option) if not loaded_property: if set_default: log.debug('Setting default Cassandra %s to %s', config_option, default) loaded_property = default else: log.error('No cassandra %s specified in the configuration or passed to the module.', config_option) raise CommandExecutionError("ERROR: Cassandra {0} cannot be empty.".format(config_option)) return loaded_property return property_name def _get_ssl_opts(): ''' Parse out ssl_options for Cassandra cluster connection. Make sure that the ssl_version (if any specified) is valid. ''' sslopts = __salt__['config.option']('cassandra').get('ssl_options', None) ssl_opts = {} if sslopts: ssl_opts['ca_certs'] = sslopts['ca_certs'] if SSL_VERSION in sslopts: if not sslopts[SSL_VERSION].startswith('PROTOCOL_'): valid_opts = ', '.join( [x for x in dir(ssl) if x.startswith('PROTOCOL_')] ) raise CommandExecutionError('Invalid protocol_version ' 'specified! ' 'Please make sure ' 'that the ssl protocol' 'version is one from the SSL' 'module. ' 'Valid options are ' '{0}'.format(valid_opts)) else: ssl_opts[SSL_VERSION] = \ getattr(ssl, sslopts[SSL_VERSION]) return ssl_opts else: return None def _connect(contact_points=None, port=None, cql_user=None, cql_pass=None, protocol_version=None): ''' Connect to a Cassandra cluster. :param contact_points: The Cassandra cluster addresses, can either be a string or a list of IPs. :type contact_points: str or list of str :param cql_user: The Cassandra user if authentication is turned on. :type cql_user: str :param cql_pass: The Cassandra user password if authentication is turned on. :type cql_pass: str :param port: The Cassandra cluster port, defaults to None. :type port: int :param protocol_version: Cassandra protocol version to use. :type port: int :return: The session and cluster objects. :rtype: cluster object, session object ''' # Lazy load the Cassandra cluster and session for this module by creating a # cluster and session when cql_query is called the first time. Get the # Cassandra cluster and session from this module's __context__ after it is # loaded the first time cql_query is called. # # TODO: Call cluster.shutdown() when the module is unloaded on # master/minion shutdown. Currently, Master.shutdown() and Minion.shutdown() # do nothing to allow loaded modules to gracefully handle resources stored # in __context__ (i.e. connection pools). This means that the connection # pool is orphaned and Salt relies on Cassandra to reclaim connections. # Perhaps if Master/Minion daemons could be enhanced to call an "__unload__" # function, or something similar for each loaded module, connection pools # and the like can be gracefully reclaimed/shutdown. if (__context__ and 'cassandra_cql_returner_cluster' in __context__ and 'cassandra_cql_returner_session' in __context__): return __context__['cassandra_cql_returner_cluster'], __context__['cassandra_cql_returner_session'] else: contact_points = _load_properties(property_name=contact_points, config_option='cluster') contact_points = contact_points if isinstance(contact_points, list) else contact_points.split(',') port = _load_properties(property_name=port, config_option='port', set_default=True, default=9042) cql_user = _load_properties(property_name=cql_user, config_option='username', set_default=True, default="cassandra") cql_pass = _load_properties(property_name=cql_pass, config_option='password', set_default=True, default="cassandra") protocol_version = _load_properties(property_name=protocol_version, config_option='protocol_version', set_default=True, default=4) try: auth_provider = PlainTextAuthProvider(username=cql_user, password=cql_pass) ssl_opts = _get_ssl_opts() if ssl_opts: cluster = Cluster(contact_points, port=port, auth_provider=auth_provider, ssl_options=ssl_opts, protocol_version=protocol_version, compression=True) else: cluster = Cluster(contact_points, port=port, auth_provider=auth_provider, protocol_version=protocol_version, compression=True) for recontimes in range(1, 4): try: session = cluster.connect() break except OperationTimedOut: log.warning('Cassandra cluster.connect timed out, try %s', recontimes) if recontimes >= 3: raise # TODO: Call cluster.shutdown() when the module is unloaded on shutdown. __context__['cassandra_cql_returner_cluster'] = cluster __context__['cassandra_cql_returner_session'] = session __context__['cassandra_cql_prepared'] = {} log.debug('Successfully connected to Cassandra cluster at %s', contact_points) return cluster, session except TypeError: pass except (ConnectionException, ConnectionShutdown, NoHostAvailable): log.error('Could not connect to Cassandra cluster at %s', contact_points) raise CommandExecutionError('ERROR: Could not connect to Cassandra cluster.') def cql_query_with_prepare(query, statement_name, statement_arguments, callback_errors=None, contact_points=None, port=None, cql_user=None, cql_pass=None, **kwargs): ''' Run a query on a Cassandra cluster and return a dictionary. This function should not be used asynchronously for SELECTs -- it will not return anything and we don't currently have a mechanism for handling a future that will return results. :param query: The query to execute. :type query: str :param statement_name: Name to assign the prepared statement in the __context__ dictionary :type statement_name: str :param statement_arguments: Bind parameters for the SQL statement :type statement_arguments: list[str] :param async: Run this query in asynchronous mode :type async: bool :param callback_errors: Function to call after query runs if there is an error :type callback_errors: Function callable :param contact_points: The Cassandra cluster addresses, can either be a string or a list of IPs. :type contact_points: str | list[str] :param cql_user: The Cassandra user if authentication is turned on. :type cql_user: str :param cql_pass: The Cassandra user password if authentication is turned on. :type cql_pass: str :param port: The Cassandra cluster port, defaults to None. :type port: int :param params: The parameters for the query, optional. :type params: str :return: A dictionary from the return values of the query :rtype: list[dict] CLI Example: .. code-block:: bash # Insert data asynchronously salt this-node cassandra_cql.cql_query_with_prepare "name_insert" "INSERT INTO USERS (first_name, last_name) VALUES (?, ?)" \ statement_arguments=['John','Doe'], asynchronous=True # Select data, should not be asynchronous because there is not currently a facility to return data from a future salt this-node cassandra_cql.cql_query_with_prepare "name_select" "SELECT * FROM USERS WHERE first_name=?" \ statement_arguments=['John'] ''' # Backward-compatibility with Python 3.7: "async" is a reserved word asynchronous = kwargs.get('async', False) try: cluster, session = _connect(contact_points=contact_points, port=port, cql_user=cql_user, cql_pass=cql_pass) except CommandExecutionError: log.critical('Could not get Cassandra cluster session.') raise except BaseException as e: log.critical('Unexpected error while getting Cassandra cluster session: %s', e) raise if statement_name not in __context__['cassandra_cql_prepared']: try: bound_statement = session.prepare(query) __context__['cassandra_cql_prepared'][statement_name] = bound_statement except BaseException as e: log.critical('Unexpected error while preparing SQL statement: %s', e) raise else: bound_statement = __context__['cassandra_cql_prepared'][statement_name] session.row_factory = dict_factory ret = [] try: if asynchronous: future_results = session.execute_async(bound_statement.bind(statement_arguments)) # future_results.add_callbacks(_async_log_errors) else: results = session.execute(bound_statement.bind(statement_arguments)) except BaseException as e: log.error('Failed to execute query: %s\n reason: %s', query, e) msg = "ERROR: Cassandra query failed: {0} reason: {1}".format(query, e) raise CommandExecutionError(msg) if not asynchronous and results: for result in results: values = {} for key, value in six.iteritems(result): # Salt won't return dictionaries with odd types like uuid.UUID if not isinstance(value, six.text_type): # Must support Cassandra collection types. # Namely, Cassandras set, list, and map collections. if not isinstance(value, (set, list, dict)): value = six.text_type(value) values[key] = value ret.append(values) # If this was a synchronous call, then we either have an empty list # because there was no return, or we have a return # If this was an asynchronous call we only return the empty list return ret def version(contact_points=None, port=None, cql_user=None, cql_pass=None): ''' Show the Cassandra version. :param contact_points: The Cassandra cluster addresses, can either be a string or a list of IPs. :type contact_points: str | list[str] :param cql_user: The Cassandra user if authentication is turned on. :type cql_user: str :param cql_pass: The Cassandra user password if authentication is turned on. :type cql_pass: str :param port: The Cassandra cluster port, defaults to None. :type port: int :return: The version for this Cassandra cluster. :rtype: str CLI Example: .. code-block:: bash salt 'minion1' cassandra_cql.version salt 'minion1' cassandra_cql.version contact_points=minion1 ''' query = '''select release_version from system.local limit 1;''' try: ret = cql_query(query, contact_points, port, cql_user, cql_pass) except CommandExecutionError: log.critical('Could not get Cassandra version.') raise except BaseException as e: log.critical('Unexpected error while getting Cassandra version: %s', e) raise return ret[0].get('release_version') def info(contact_points=None, port=None, cql_user=None, cql_pass=None): ''' Show the Cassandra information for this cluster. :param contact_points: The Cassandra cluster addresses, can either be a string or a list of IPs. :type contact_points: str | list[str] :param cql_user: The Cassandra user if authentication is turned on. :type cql_user: str :param cql_pass: The Cassandra user password if authentication is turned on. :type cql_pass: str :param port: The Cassandra cluster port, defaults to None. :type port: int :return: The information for this Cassandra cluster. :rtype: dict CLI Example: .. code-block:: bash salt 'minion1' cassandra_cql.info salt 'minion1' cassandra_cql.info contact_points=minion1 ''' query = '''select cluster_name, data_center, partitioner, host_id, rack, release_version, cql_version, schema_version, thrift_version from system.local limit 1;''' ret = {} try: ret = cql_query(query, contact_points, port, cql_user, cql_pass) except CommandExecutionError: log.critical('Could not list Cassandra info.') raise except BaseException as e: log.critical('Unexpected error while listing Cassandra info: %s', e) raise return ret def list_keyspaces(contact_points=None, port=None, cql_user=None, cql_pass=None): ''' List keyspaces in a Cassandra cluster. :param contact_points: The Cassandra cluster addresses, can either be a string or a list of IPs. :type contact_points: str | list[str] :param cql_user: The Cassandra user if authentication is turned on. :type cql_user: str :param cql_pass: The Cassandra user password if authentication is turned on. :type cql_pass: str :param port: The Cassandra cluster port, defaults to None. :type port: int :return: The keyspaces in this Cassandra cluster. :rtype: list[dict] CLI Example: .. code-block:: bash salt 'minion1' cassandra_cql.list_keyspaces salt 'minion1' cassandra_cql.list_keyspaces contact_points=minion1 port=9000 ''' query = { '2': 'select keyspace_name from system.schema_keyspaces;', '3': 'select keyspace_name from system_schema.keyspaces;', } ret = {} try: ret = cql_query(query, contact_points, port, cql_user, cql_pass) except CommandExecutionError: log.critical('Could not list keyspaces.') raise except BaseException as e: log.critical('Unexpected error while listing keyspaces: %s', e) raise return ret def list_column_families(keyspace=None, contact_points=None, port=None, cql_user=None, cql_pass=None): ''' List column families in a Cassandra cluster for all keyspaces or just the provided one. :param keyspace: The keyspace to provide the column families for, optional. :type keyspace: str :param contact_points: The Cassandra cluster addresses, can either be a string or a list of IPs. :type contact_points: str | list[str] :param cql_user: The Cassandra user if authentication is turned on. :type cql_user: str :param cql_pass: The Cassandra user password if authentication is turned on. :type cql_pass: str :param port: The Cassandra cluster port, defaults to None. :type port: int :return: The column families in this Cassandra cluster. :rtype: list[dict] CLI Example: .. code-block:: bash salt 'minion1' cassandra_cql.list_column_families salt 'minion1' cassandra_cql.list_column_families contact_points=minion1 salt 'minion1' cassandra_cql.list_column_families keyspace=system ''' where_clause = "where keyspace_name = '{0}'".format(keyspace) if keyspace else "" query = { '2': '''select columnfamily_name from system.schema_columnfamilies {0};'''.format(where_clause), '3': '''select column_name from system_schema.columns {0};'''.format(where_clause), } ret = {} try: ret = cql_query(query, contact_points, port, cql_user, cql_pass) except CommandExecutionError: log.critical('Could not list column families.') raise except BaseException as e: log.critical('Unexpected error while listing column families: %s', e) raise return ret def keyspace_exists(keyspace, contact_points=None, port=None, cql_user=None, cql_pass=None): ''' Check if a keyspace exists in a Cassandra cluster. :param keyspace The keyspace name to check for. :type keyspace: str :param contact_points: The Cassandra cluster addresses, can either be a string or a list of IPs. :type contact_points: str | list[str] :param cql_user: The Cassandra user if authentication is turned on. :type cql_user: str :param cql_pass: The Cassandra user password if authentication is turned on. :type cql_pass: str :param port: The Cassandra cluster port, defaults to None. :type port: int :return: The info for the keyspace or False if it does not exist. :rtype: dict CLI Example: .. code-block:: bash salt 'minion1' cassandra_cql.keyspace_exists keyspace=system ''' query = { '2': '''select keyspace_name from system.schema_keyspaces where keyspace_name = '{0}';'''.format(keyspace), '3': '''select keyspace_name from system_schema.keyspaces where keyspace_name = '{0}';'''.format(keyspace), } try: ret = cql_query(query, contact_points, port, cql_user, cql_pass) except CommandExecutionError: log.critical('Could not determine if keyspace exists.') raise except BaseException as e: log.critical('Unexpected error while determining if keyspace exists: %s', e) raise return True if ret else False def create_keyspace(keyspace, replication_strategy='SimpleStrategy', replication_factor=1, replication_datacenters=None, contact_points=None, port=None, cql_user=None, cql_pass=None): ''' Create a new keyspace in Cassandra. :param keyspace: The keyspace name :type keyspace: str :param replication_strategy: either `SimpleStrategy` or `NetworkTopologyStrategy` :type replication_strategy: str :param replication_factor: number of replicas of data on multiple nodes. not used if using NetworkTopologyStrategy :type replication_factor: int :param replication_datacenters: string or dict of datacenter names to replication factors, required if using NetworkTopologyStrategy (will be a dict if coming from state file). :type replication_datacenters: str | dict[str, int] :param contact_points: The Cassandra cluster addresses, can either be a string or a list of IPs. :type contact_points: str | list[str] :param cql_user: The Cassandra user if authentication is turned on. :type cql_user: str :param cql_pass: The Cassandra user password if authentication is turned on. :type cql_pass: str :param port: The Cassandra cluster port, defaults to None. :type port: int :return: The info for the keyspace or False if it does not exist. :rtype: dict CLI Example: .. code-block:: bash # CLI Example: salt 'minion1' cassandra_cql.create_keyspace keyspace=newkeyspace salt 'minion1' cassandra_cql.create_keyspace keyspace=newkeyspace replication_strategy=NetworkTopologyStrategy \ replication_datacenters='{"datacenter_1": 3, "datacenter_2": 2}' ''' existing_keyspace = keyspace_exists(keyspace, contact_points, port) if not existing_keyspace: # Add the strategy, replication_factor, etc. replication_map = { 'class': replication_strategy } if replication_datacenters: if isinstance(replication_datacenters, six.string_types): try: replication_datacenter_map = salt.utils.json.loads(replication_datacenters) replication_map.update(**replication_datacenter_map) except BaseException: # pylint: disable=W0703 log.error("Could not load json replication_datacenters.") return False else: replication_map.update(**replication_datacenters) else: replication_map['replication_factor'] = replication_factor query = '''create keyspace {0} with replication = {1} and durable_writes = true;'''.format(keyspace, replication_map) try: cql_query(query, contact_points, port, cql_user, cql_pass) except CommandExecutionError: log.critical('Could not create keyspace.') raise except BaseException as e: log.critical('Unexpected error while creating keyspace: %s', e) raise def drop_keyspace(keyspace, contact_points=None, port=None, cql_user=None, cql_pass=None): ''' Drop a keyspace if it exists in a Cassandra cluster. :param keyspace: The keyspace to drop. :type keyspace: str :param contact_points: The Cassandra cluster addresses, can either be a string or a list of IPs. :type contact_points: str | list[str] :param cql_user: The Cassandra user if authentication is turned on. :type cql_user: str :param cql_pass: The Cassandra user password if authentication is turned on. :type cql_pass: str :param port: The Cassandra cluster port, defaults to None. :type port: int :return: The info for the keyspace or False if it does not exist. :rtype: dict CLI Example: .. code-block:: bash salt 'minion1' cassandra_cql.drop_keyspace keyspace=test salt 'minion1' cassandra_cql.drop_keyspace keyspace=test contact_points=minion1 ''' existing_keyspace = keyspace_exists(keyspace, contact_points, port) if existing_keyspace: query = '''drop keyspace {0};'''.format(keyspace) try: cql_query(query, contact_points, port, cql_user, cql_pass) except CommandExecutionError: log.critical('Could not drop keyspace.') raise except BaseException as e: log.critical('Unexpected error while dropping keyspace: %s', e) raise return True def list_users(contact_points=None, port=None, cql_user=None, cql_pass=None): ''' List existing users in this Cassandra cluster. :param contact_points: The Cassandra cluster addresses, can either be a string or a list of IPs. :type contact_points: str | list[str] :param port: The Cassandra cluster port, defaults to None. :type port: int :param cql_user: The Cassandra user if authentication is turned on. :type cql_user: str :param cql_pass: The Cassandra user password if authentication is turned on. :type cql_pass: str :return: The list of existing users. :rtype: dict CLI Example: .. code-block:: bash salt 'minion1' cassandra_cql.list_users salt 'minion1' cassandra_cql.list_users contact_points=minion1 ''' query = "list users;" ret = {} try: ret = cql_query(query, contact_points, port, cql_user, cql_pass) except CommandExecutionError: log.critical('Could not list users.') raise except BaseException as e: log.critical('Unexpected error while listing users: %s', e) raise return ret def create_user(username, password, superuser=False, contact_points=None, port=None, cql_user=None, cql_pass=None): ''' Create a new cassandra user with credentials and superuser status. :param username: The name of the new user. :type username: str :param password: The password of the new user. :type password: str :param superuser: Is the new user going to be a superuser? default: False :type superuser: bool :param contact_points: The Cassandra cluster addresses, can either be a string or a list of IPs. :type contact_points: str | list[str] :param cql_user: The Cassandra user if authentication is turned on. :type cql_user: str :param cql_pass: The Cassandra user password if authentication is turned on. :type cql_pass: str :param port: The Cassandra cluster port, defaults to None. :type port: int :return: :rtype: CLI Example: .. code-block:: bash salt 'minion1' cassandra_cql.create_user username=joe password=secret salt 'minion1' cassandra_cql.create_user username=joe password=secret superuser=True salt 'minion1' cassandra_cql.create_user username=joe password=secret superuser=True contact_points=minion1 ''' superuser_cql = 'superuser' if superuser else 'nosuperuser' query = '''create user if not exists {0} with password '{1}' {2};'''.format(username, password, superuser_cql) log.debug("Attempting to create a new user with username=%s superuser=%s", username, superuser_cql) # The create user query doesn't actually return anything if the query succeeds. # If the query fails, catch the exception, log a messange and raise it again. try: cql_query(query, contact_points, port, cql_user, cql_pass) except CommandExecutionError: log.critical('Could not create user.') raise except BaseException as e: log.critical('Unexpected error while creating user: %s', e) raise return True def create_role(username, password, superuser=False, login=False, contact_points=None, port=None, cql_user=None, cql_pass=None): ''' Create a new cassandra role with credentials and superuser status. :param username: The name of the new user. :type username: str :param password: The password of the new user. :type password: str :param superuser: Is the new role going to be a superuser? default: False :type superuser: bool :param login: Is the new role going to be allowed to log in? default: False :type superuser: bool :param contact_points: The Cassandra cluster addresses, can either be a string or a list of IPs. :type contact_points: str | list[str] :param cql_user: The Cassandra user if authentication is turned on. :type cql_user: str :param cql_pass: The Cassandra user password if authentication is turned on. :type cql_pass: str :param port: The Cassandra cluster port, defaults to None. :type port: int :return: :rtype: CLI Example: .. code-block:: bash salt 'minion1' cassandra_cql.create_role username=joe password=secret salt 'minion1' cassandra_cql.create_role username=joe password=secret superuser=True salt 'minion1' cassandra_cql.create_role username=joe password=secret superuser=True login=True salt 'minion1' cassandra_cql.create_role username=joe password=secret superuser=True login=True contact_points=minion1 ''' superuser_cql = 'superuser = true' if superuser else 'superuser = false' login_cql = 'login = true' if login else 'login = false' query = '''create role if not exists {0} with password '{1}' and {2} and {3} ;'''.format(username, password, superuser_cql, login_cql) log.debug("Attempting to create a new role with username=%s superuser=%s login=%s", username, superuser, login) # The create role query doesn't actually return anything if the query succeeds. # If the query fails, catch the exception, log a messange and raise it again. try: cql_query(query, contact_points, port, cql_user, cql_pass) except CommandExecutionError: log.critical('Could not create role.') raise except BaseException as e: log.critical('Unexpected error while creating role: %s', e) raise return True def list_permissions(username=None, resource=None, resource_type='keyspace', permission=None, contact_points=None, port=None, cql_user=None, cql_pass=None): ''' List permissions. :param username: The name of the user to list permissions for. :type username: str :param resource: The resource (keyspace or table), if None, permissions for all resources are listed. :type resource: str :param resource_type: The resource_type (keyspace or table), defaults to 'keyspace'. :type resource_type: str :param permission: A permission name (e.g. select), if None, all permissions are listed. :type permission: str :param contact_points: The Cassandra cluster addresses, can either be a string or a list of IPs. :type contact_points: str | list[str] :param cql_user: The Cassandra user if authentication is turned on. :type cql_user: str :param cql_pass: The Cassandra user password if authentication is turned on. :type cql_pass: str :param port: The Cassandra cluster port, defaults to None. :type port: int :return: Dictionary of permissions. :rtype: dict CLI Example: .. code-block:: bash salt 'minion1' cassandra_cql.list_permissions salt 'minion1' cassandra_cql.list_permissions username=joe resource=test_keyspace permission=select salt 'minion1' cassandra_cql.list_permissions username=joe resource=test_table resource_type=table \ permission=select contact_points=minion1 ''' keyspace_cql = "{0} {1}".format(resource_type, resource) if resource else "all keyspaces" permission_cql = "{0} permission".format(permission) if permission else "all permissions" query = "list {0} on {1}".format(permission_cql, keyspace_cql) if username: query = "{0} of {1}".format(query, username) log.debug("Attempting to list permissions with query '%s'", query) ret = {} try: ret = cql_query(query, contact_points, port, cql_user, cql_pass) except CommandExecutionError: log.critical('Could not list permissions.') raise except BaseException as e: log.critical('Unexpected error while listing permissions: %s', e) raise return ret def grant_permission(username, resource=None, resource_type='keyspace', permission=None, contact_points=None, port=None, cql_user=None, cql_pass=None): ''' Grant permissions to a user. :param username: The name of the user to grant permissions to. :type username: str :param resource: The resource (keyspace or table), if None, permissions for all resources are granted. :type resource: str :param resource_type: The resource_type (keyspace or table), defaults to 'keyspace'. :type resource_type: str :param permission: A permission name (e.g. select), if None, all permissions are granted. :type permission: str :param contact_points: The Cassandra cluster addresses, can either be a string or a list of IPs. :type contact_points: str | list[str] :param cql_user: The Cassandra user if authentication is turned on. :type cql_user: str :param cql_pass: The Cassandra user password if authentication is turned on. :type cql_pass: str :param port: The Cassandra cluster port, defaults to None. :type port: int :return: :rtype: CLI Example: .. code-block:: bash salt 'minion1' cassandra_cql.grant_permission salt 'minion1' cassandra_cql.grant_permission username=joe resource=test_keyspace permission=select salt 'minion1' cassandra_cql.grant_permission username=joe resource=test_table resource_type=table \ permission=select contact_points=minion1 ''' permission_cql = "grant {0}".format(permission) if permission else "grant all permissions" resource_cql = "on {0} {1}".format(resource_type, resource) if resource else "on all keyspaces" query = "{0} {1} to {2}".format(permission_cql, resource_cql, username) log.debug("Attempting to grant permissions with query '%s'", query) try: cql_query(query, contact_points, port, cql_user, cql_pass) except CommandExecutionError: log.critical('Could not grant permissions.') raise except BaseException as e: log.critical('Unexpected error while granting permissions: %s', e) raise return True
saltstack/salt
salt/modules/cassandra_cql.py
cql_query_with_prepare
python
def cql_query_with_prepare(query, statement_name, statement_arguments, callback_errors=None, contact_points=None, port=None, cql_user=None, cql_pass=None, **kwargs): ''' Run a query on a Cassandra cluster and return a dictionary. This function should not be used asynchronously for SELECTs -- it will not return anything and we don't currently have a mechanism for handling a future that will return results. :param query: The query to execute. :type query: str :param statement_name: Name to assign the prepared statement in the __context__ dictionary :type statement_name: str :param statement_arguments: Bind parameters for the SQL statement :type statement_arguments: list[str] :param async: Run this query in asynchronous mode :type async: bool :param callback_errors: Function to call after query runs if there is an error :type callback_errors: Function callable :param contact_points: The Cassandra cluster addresses, can either be a string or a list of IPs. :type contact_points: str | list[str] :param cql_user: The Cassandra user if authentication is turned on. :type cql_user: str :param cql_pass: The Cassandra user password if authentication is turned on. :type cql_pass: str :param port: The Cassandra cluster port, defaults to None. :type port: int :param params: The parameters for the query, optional. :type params: str :return: A dictionary from the return values of the query :rtype: list[dict] CLI Example: .. code-block:: bash # Insert data asynchronously salt this-node cassandra_cql.cql_query_with_prepare "name_insert" "INSERT INTO USERS (first_name, last_name) VALUES (?, ?)" \ statement_arguments=['John','Doe'], asynchronous=True # Select data, should not be asynchronous because there is not currently a facility to return data from a future salt this-node cassandra_cql.cql_query_with_prepare "name_select" "SELECT * FROM USERS WHERE first_name=?" \ statement_arguments=['John'] ''' # Backward-compatibility with Python 3.7: "async" is a reserved word asynchronous = kwargs.get('async', False) try: cluster, session = _connect(contact_points=contact_points, port=port, cql_user=cql_user, cql_pass=cql_pass) except CommandExecutionError: log.critical('Could not get Cassandra cluster session.') raise except BaseException as e: log.critical('Unexpected error while getting Cassandra cluster session: %s', e) raise if statement_name not in __context__['cassandra_cql_prepared']: try: bound_statement = session.prepare(query) __context__['cassandra_cql_prepared'][statement_name] = bound_statement except BaseException as e: log.critical('Unexpected error while preparing SQL statement: %s', e) raise else: bound_statement = __context__['cassandra_cql_prepared'][statement_name] session.row_factory = dict_factory ret = [] try: if asynchronous: future_results = session.execute_async(bound_statement.bind(statement_arguments)) # future_results.add_callbacks(_async_log_errors) else: results = session.execute(bound_statement.bind(statement_arguments)) except BaseException as e: log.error('Failed to execute query: %s\n reason: %s', query, e) msg = "ERROR: Cassandra query failed: {0} reason: {1}".format(query, e) raise CommandExecutionError(msg) if not asynchronous and results: for result in results: values = {} for key, value in six.iteritems(result): # Salt won't return dictionaries with odd types like uuid.UUID if not isinstance(value, six.text_type): # Must support Cassandra collection types. # Namely, Cassandras set, list, and map collections. if not isinstance(value, (set, list, dict)): value = six.text_type(value) values[key] = value ret.append(values) # If this was a synchronous call, then we either have an empty list # because there was no return, or we have a return # If this was an asynchronous call we only return the empty list return ret
Run a query on a Cassandra cluster and return a dictionary. This function should not be used asynchronously for SELECTs -- it will not return anything and we don't currently have a mechanism for handling a future that will return results. :param query: The query to execute. :type query: str :param statement_name: Name to assign the prepared statement in the __context__ dictionary :type statement_name: str :param statement_arguments: Bind parameters for the SQL statement :type statement_arguments: list[str] :param async: Run this query in asynchronous mode :type async: bool :param callback_errors: Function to call after query runs if there is an error :type callback_errors: Function callable :param contact_points: The Cassandra cluster addresses, can either be a string or a list of IPs. :type contact_points: str | list[str] :param cql_user: The Cassandra user if authentication is turned on. :type cql_user: str :param cql_pass: The Cassandra user password if authentication is turned on. :type cql_pass: str :param port: The Cassandra cluster port, defaults to None. :type port: int :param params: The parameters for the query, optional. :type params: str :return: A dictionary from the return values of the query :rtype: list[dict] CLI Example: .. code-block:: bash # Insert data asynchronously salt this-node cassandra_cql.cql_query_with_prepare "name_insert" "INSERT INTO USERS (first_name, last_name) VALUES (?, ?)" \ statement_arguments=['John','Doe'], asynchronous=True # Select data, should not be asynchronous because there is not currently a facility to return data from a future salt this-node cassandra_cql.cql_query_with_prepare "name_select" "SELECT * FROM USERS WHERE first_name=?" \ statement_arguments=['John']
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/cassandra_cql.py#L365-L462
[ "def iteritems(d, **kw):\n return d.iteritems(**kw)\n", "def _connect(contact_points=None, port=None, cql_user=None, cql_pass=None,\n protocol_version=None):\n '''\n Connect to a Cassandra cluster.\n\n :param contact_points: The Cassandra cluster addresses, can either be a string or a list of IPs.\n :type contact_points: str or list of str\n :param cql_user: The Cassandra user if authentication is turned on.\n :type cql_user: str\n :param cql_pass: The Cassandra user password if authentication is turned on.\n :type cql_pass: str\n :param port: The Cassandra cluster port, defaults to None.\n :type port: int\n :param protocol_version: Cassandra protocol version to use.\n :type port: int\n :return: The session and cluster objects.\n :rtype: cluster object, session object\n '''\n # Lazy load the Cassandra cluster and session for this module by creating a\n # cluster and session when cql_query is called the first time. Get the\n # Cassandra cluster and session from this module's __context__ after it is\n # loaded the first time cql_query is called.\n #\n # TODO: Call cluster.shutdown() when the module is unloaded on\n # master/minion shutdown. Currently, Master.shutdown() and Minion.shutdown()\n # do nothing to allow loaded modules to gracefully handle resources stored\n # in __context__ (i.e. connection pools). This means that the connection\n # pool is orphaned and Salt relies on Cassandra to reclaim connections.\n # Perhaps if Master/Minion daemons could be enhanced to call an \"__unload__\"\n # function, or something similar for each loaded module, connection pools\n # and the like can be gracefully reclaimed/shutdown.\n if (__context__\n and 'cassandra_cql_returner_cluster' in __context__\n and 'cassandra_cql_returner_session' in __context__):\n return __context__['cassandra_cql_returner_cluster'], __context__['cassandra_cql_returner_session']\n else:\n\n contact_points = _load_properties(property_name=contact_points, config_option='cluster')\n contact_points = contact_points if isinstance(contact_points, list) else contact_points.split(',')\n port = _load_properties(property_name=port, config_option='port', set_default=True, default=9042)\n cql_user = _load_properties(property_name=cql_user, config_option='username', set_default=True, default=\"cassandra\")\n cql_pass = _load_properties(property_name=cql_pass, config_option='password', set_default=True, default=\"cassandra\")\n protocol_version = _load_properties(property_name=protocol_version,\n config_option='protocol_version',\n set_default=True, default=4)\n\n try:\n auth_provider = PlainTextAuthProvider(username=cql_user, password=cql_pass)\n ssl_opts = _get_ssl_opts()\n if ssl_opts:\n cluster = Cluster(contact_points,\n port=port,\n auth_provider=auth_provider,\n ssl_options=ssl_opts,\n protocol_version=protocol_version,\n compression=True)\n else:\n cluster = Cluster(contact_points, port=port,\n auth_provider=auth_provider,\n protocol_version=protocol_version,\n compression=True)\n for recontimes in range(1, 4):\n try:\n session = cluster.connect()\n break\n except OperationTimedOut:\n log.warning('Cassandra cluster.connect timed out, try %s', recontimes)\n if recontimes >= 3:\n raise\n\n # TODO: Call cluster.shutdown() when the module is unloaded on shutdown.\n __context__['cassandra_cql_returner_cluster'] = cluster\n __context__['cassandra_cql_returner_session'] = session\n __context__['cassandra_cql_prepared'] = {}\n\n log.debug('Successfully connected to Cassandra cluster at %s', contact_points)\n return cluster, session\n except TypeError:\n pass\n except (ConnectionException, ConnectionShutdown, NoHostAvailable):\n log.error('Could not connect to Cassandra cluster at %s', contact_points)\n raise CommandExecutionError('ERROR: Could not connect to Cassandra cluster.')\n" ]
# -*- coding: utf-8 -*- ''' Cassandra Database Module .. versionadded:: 2015.5.0 This module works with Cassandra v2 and v3 and hence generates queries based on the internal schema of said version. :depends: DataStax Python Driver for Apache Cassandra https://github.com/datastax/python-driver pip install cassandra-driver :referenced by: Salt's cassandra_cql returner :configuration: The Cassandra cluster members and connection port can either be specified in the master or minion config, the minion's pillar or be passed to the module. Example configuration in the config for a single node: .. code-block:: yaml cassandra: cluster: 192.168.50.10 port: 9000 Example configuration in the config for a cluster: .. code-block:: yaml cassandra: cluster: - 192.168.50.10 - 192.168.50.11 - 192.168.50.12 port: 9000 username: cas_admin .. versionchanged:: 2016.11.0 Added support for ``ssl_options`` and ``protocol_version``. Example configuration with `ssl options <http://datastax.github.io/python-driver/api/cassandra/cluster.html#cassandra.cluster.Cluster.ssl_options>`_: If ``ssl_options`` are present in cassandra config the cassandra_cql returner will use SSL. SSL isn't used if ``ssl_options`` isn't specified. .. code-block:: yaml cassandra: cluster: - 192.168.50.10 - 192.168.50.11 - 192.168.50.12 port: 9000 username: cas_admin ssl_options: ca_certs: /etc/ssl/certs/ca-bundle.trust.crt # SSL version should be one from the ssl module # This is an optional parameter ssl_version: PROTOCOL_TLSv1 Additionally you can also specify the ``protocol_version`` to `use <http://datastax.github.io/python-driver/api/cassandra/cluster.html#cassandra.cluster.Cluster.ssl_options>`_. .. code-block:: yaml cassandra: cluster: - 192.168.50.10 - 192.168.50.11 - 192.168.50.12 port: 9000 username: cas_admin # defaults to 4, if not set protocol_version: 3 ''' # Import Python Libs from __future__ import absolute_import, unicode_literals, print_function import logging import re import ssl # Import Salt Libs import salt.utils.json from salt.exceptions import CommandExecutionError # Import 3rd-party libs from salt.ext import six from salt.ext.six.moves import range import salt.utils.versions SSL_VERSION = 'ssl_version' log = logging.getLogger(__name__) __virtualname__ = 'cassandra_cql' HAS_DRIVER = False try: # pylint: disable=import-error,no-name-in-module from cassandra.cluster import Cluster from cassandra.cluster import NoHostAvailable from cassandra.connection import ConnectionException, \ ConnectionShutdown, OperationTimedOut from cassandra.auth import PlainTextAuthProvider from cassandra.query import dict_factory # pylint: enable=import-error,no-name-in-module HAS_DRIVER = True except ImportError: pass def __virtual__(): ''' Return virtual name of the module only if the python driver can be loaded. :return: The virtual name of the module. :rtype: str ''' if HAS_DRIVER: return __virtualname__ return (False, 'Cannot load cassandra_cql module: python driver not found') def _async_log_errors(errors): log.error('Cassandra_cql asynchronous call returned: %s', errors) def _load_properties(property_name, config_option, set_default=False, default=None): ''' Load properties for the cassandra module from config or pillar. :param property_name: The property to load. :type property_name: str or list of str :param config_option: The name of the config option. :type config_option: str :param set_default: Should a default be set if not found in config. :type set_default: bool :param default: The default value to be set. :type default: str or int :return: The property fetched from the configuration or default. :rtype: str or list of str ''' if not property_name: log.debug("No property specified in function, trying to load from salt configuration") try: options = __salt__['config.option']('cassandra') except BaseException as e: log.error("Failed to get cassandra config options. Reason: %s", e) raise loaded_property = options.get(config_option) if not loaded_property: if set_default: log.debug('Setting default Cassandra %s to %s', config_option, default) loaded_property = default else: log.error('No cassandra %s specified in the configuration or passed to the module.', config_option) raise CommandExecutionError("ERROR: Cassandra {0} cannot be empty.".format(config_option)) return loaded_property return property_name def _get_ssl_opts(): ''' Parse out ssl_options for Cassandra cluster connection. Make sure that the ssl_version (if any specified) is valid. ''' sslopts = __salt__['config.option']('cassandra').get('ssl_options', None) ssl_opts = {} if sslopts: ssl_opts['ca_certs'] = sslopts['ca_certs'] if SSL_VERSION in sslopts: if not sslopts[SSL_VERSION].startswith('PROTOCOL_'): valid_opts = ', '.join( [x for x in dir(ssl) if x.startswith('PROTOCOL_')] ) raise CommandExecutionError('Invalid protocol_version ' 'specified! ' 'Please make sure ' 'that the ssl protocol' 'version is one from the SSL' 'module. ' 'Valid options are ' '{0}'.format(valid_opts)) else: ssl_opts[SSL_VERSION] = \ getattr(ssl, sslopts[SSL_VERSION]) return ssl_opts else: return None def _connect(contact_points=None, port=None, cql_user=None, cql_pass=None, protocol_version=None): ''' Connect to a Cassandra cluster. :param contact_points: The Cassandra cluster addresses, can either be a string or a list of IPs. :type contact_points: str or list of str :param cql_user: The Cassandra user if authentication is turned on. :type cql_user: str :param cql_pass: The Cassandra user password if authentication is turned on. :type cql_pass: str :param port: The Cassandra cluster port, defaults to None. :type port: int :param protocol_version: Cassandra protocol version to use. :type port: int :return: The session and cluster objects. :rtype: cluster object, session object ''' # Lazy load the Cassandra cluster and session for this module by creating a # cluster and session when cql_query is called the first time. Get the # Cassandra cluster and session from this module's __context__ after it is # loaded the first time cql_query is called. # # TODO: Call cluster.shutdown() when the module is unloaded on # master/minion shutdown. Currently, Master.shutdown() and Minion.shutdown() # do nothing to allow loaded modules to gracefully handle resources stored # in __context__ (i.e. connection pools). This means that the connection # pool is orphaned and Salt relies on Cassandra to reclaim connections. # Perhaps if Master/Minion daemons could be enhanced to call an "__unload__" # function, or something similar for each loaded module, connection pools # and the like can be gracefully reclaimed/shutdown. if (__context__ and 'cassandra_cql_returner_cluster' in __context__ and 'cassandra_cql_returner_session' in __context__): return __context__['cassandra_cql_returner_cluster'], __context__['cassandra_cql_returner_session'] else: contact_points = _load_properties(property_name=contact_points, config_option='cluster') contact_points = contact_points if isinstance(contact_points, list) else contact_points.split(',') port = _load_properties(property_name=port, config_option='port', set_default=True, default=9042) cql_user = _load_properties(property_name=cql_user, config_option='username', set_default=True, default="cassandra") cql_pass = _load_properties(property_name=cql_pass, config_option='password', set_default=True, default="cassandra") protocol_version = _load_properties(property_name=protocol_version, config_option='protocol_version', set_default=True, default=4) try: auth_provider = PlainTextAuthProvider(username=cql_user, password=cql_pass) ssl_opts = _get_ssl_opts() if ssl_opts: cluster = Cluster(contact_points, port=port, auth_provider=auth_provider, ssl_options=ssl_opts, protocol_version=protocol_version, compression=True) else: cluster = Cluster(contact_points, port=port, auth_provider=auth_provider, protocol_version=protocol_version, compression=True) for recontimes in range(1, 4): try: session = cluster.connect() break except OperationTimedOut: log.warning('Cassandra cluster.connect timed out, try %s', recontimes) if recontimes >= 3: raise # TODO: Call cluster.shutdown() when the module is unloaded on shutdown. __context__['cassandra_cql_returner_cluster'] = cluster __context__['cassandra_cql_returner_session'] = session __context__['cassandra_cql_prepared'] = {} log.debug('Successfully connected to Cassandra cluster at %s', contact_points) return cluster, session except TypeError: pass except (ConnectionException, ConnectionShutdown, NoHostAvailable): log.error('Could not connect to Cassandra cluster at %s', contact_points) raise CommandExecutionError('ERROR: Could not connect to Cassandra cluster.') def cql_query(query, contact_points=None, port=None, cql_user=None, cql_pass=None): ''' Run a query on a Cassandra cluster and return a dictionary. :param query: The query to execute. :type query: str :param contact_points: The Cassandra cluster addresses, can either be a string or a list of IPs. :type contact_points: str | list[str] :param cql_user: The Cassandra user if authentication is turned on. :type cql_user: str :param cql_pass: The Cassandra user password if authentication is turned on. :type cql_pass: str :param port: The Cassandra cluster port, defaults to None. :type port: int :param params: The parameters for the query, optional. :type params: str :return: A dictionary from the return values of the query :rtype: list[dict] CLI Example: .. code-block:: bash salt 'cassandra-server' cassandra_cql.cql_query "SELECT * FROM users_by_name WHERE first_name = 'jane'" ''' try: cluster, session = _connect(contact_points=contact_points, port=port, cql_user=cql_user, cql_pass=cql_pass) except CommandExecutionError: log.critical('Could not get Cassandra cluster session.') raise except BaseException as e: log.critical('Unexpected error while getting Cassandra cluster session: %s', e) raise session.row_factory = dict_factory ret = [] # Cassandra changed their internal schema from v2 to v3 # If the query contains a dictionary sorted by versions # Find the query for the current cluster version. # https://issues.apache.org/jira/browse/CASSANDRA-6717 if isinstance(query, dict): cluster_version = version(contact_points=contact_points, port=port, cql_user=cql_user, cql_pass=cql_pass) match = re.match(r'^(\d+)\.(\d+)(?:\.(\d+))?', cluster_version) major, minor, point = match.groups() # try to find the specific version in the query dictionary # then try the major version # otherwise default to the highest version number try: query = query[cluster_version] except KeyError: query = query.get(major, max(query)) log.debug('New query is: %s', query) try: results = session.execute(query) except BaseException as e: log.error('Failed to execute query: %s\n reason: %s', query, e) msg = "ERROR: Cassandra query failed: {0} reason: {1}".format(query, e) raise CommandExecutionError(msg) if results: for result in results: values = {} for key, value in six.iteritems(result): # Salt won't return dictionaries with odd types like uuid.UUID if not isinstance(value, six.text_type): # Must support Cassandra collection types. # Namely, Cassandras set, list, and map collections. if not isinstance(value, (set, list, dict)): value = six.text_type(value) values[key] = value ret.append(values) return ret def version(contact_points=None, port=None, cql_user=None, cql_pass=None): ''' Show the Cassandra version. :param contact_points: The Cassandra cluster addresses, can either be a string or a list of IPs. :type contact_points: str | list[str] :param cql_user: The Cassandra user if authentication is turned on. :type cql_user: str :param cql_pass: The Cassandra user password if authentication is turned on. :type cql_pass: str :param port: The Cassandra cluster port, defaults to None. :type port: int :return: The version for this Cassandra cluster. :rtype: str CLI Example: .. code-block:: bash salt 'minion1' cassandra_cql.version salt 'minion1' cassandra_cql.version contact_points=minion1 ''' query = '''select release_version from system.local limit 1;''' try: ret = cql_query(query, contact_points, port, cql_user, cql_pass) except CommandExecutionError: log.critical('Could not get Cassandra version.') raise except BaseException as e: log.critical('Unexpected error while getting Cassandra version: %s', e) raise return ret[0].get('release_version') def info(contact_points=None, port=None, cql_user=None, cql_pass=None): ''' Show the Cassandra information for this cluster. :param contact_points: The Cassandra cluster addresses, can either be a string or a list of IPs. :type contact_points: str | list[str] :param cql_user: The Cassandra user if authentication is turned on. :type cql_user: str :param cql_pass: The Cassandra user password if authentication is turned on. :type cql_pass: str :param port: The Cassandra cluster port, defaults to None. :type port: int :return: The information for this Cassandra cluster. :rtype: dict CLI Example: .. code-block:: bash salt 'minion1' cassandra_cql.info salt 'minion1' cassandra_cql.info contact_points=minion1 ''' query = '''select cluster_name, data_center, partitioner, host_id, rack, release_version, cql_version, schema_version, thrift_version from system.local limit 1;''' ret = {} try: ret = cql_query(query, contact_points, port, cql_user, cql_pass) except CommandExecutionError: log.critical('Could not list Cassandra info.') raise except BaseException as e: log.critical('Unexpected error while listing Cassandra info: %s', e) raise return ret def list_keyspaces(contact_points=None, port=None, cql_user=None, cql_pass=None): ''' List keyspaces in a Cassandra cluster. :param contact_points: The Cassandra cluster addresses, can either be a string or a list of IPs. :type contact_points: str | list[str] :param cql_user: The Cassandra user if authentication is turned on. :type cql_user: str :param cql_pass: The Cassandra user password if authentication is turned on. :type cql_pass: str :param port: The Cassandra cluster port, defaults to None. :type port: int :return: The keyspaces in this Cassandra cluster. :rtype: list[dict] CLI Example: .. code-block:: bash salt 'minion1' cassandra_cql.list_keyspaces salt 'minion1' cassandra_cql.list_keyspaces contact_points=minion1 port=9000 ''' query = { '2': 'select keyspace_name from system.schema_keyspaces;', '3': 'select keyspace_name from system_schema.keyspaces;', } ret = {} try: ret = cql_query(query, contact_points, port, cql_user, cql_pass) except CommandExecutionError: log.critical('Could not list keyspaces.') raise except BaseException as e: log.critical('Unexpected error while listing keyspaces: %s', e) raise return ret def list_column_families(keyspace=None, contact_points=None, port=None, cql_user=None, cql_pass=None): ''' List column families in a Cassandra cluster for all keyspaces or just the provided one. :param keyspace: The keyspace to provide the column families for, optional. :type keyspace: str :param contact_points: The Cassandra cluster addresses, can either be a string or a list of IPs. :type contact_points: str | list[str] :param cql_user: The Cassandra user if authentication is turned on. :type cql_user: str :param cql_pass: The Cassandra user password if authentication is turned on. :type cql_pass: str :param port: The Cassandra cluster port, defaults to None. :type port: int :return: The column families in this Cassandra cluster. :rtype: list[dict] CLI Example: .. code-block:: bash salt 'minion1' cassandra_cql.list_column_families salt 'minion1' cassandra_cql.list_column_families contact_points=minion1 salt 'minion1' cassandra_cql.list_column_families keyspace=system ''' where_clause = "where keyspace_name = '{0}'".format(keyspace) if keyspace else "" query = { '2': '''select columnfamily_name from system.schema_columnfamilies {0};'''.format(where_clause), '3': '''select column_name from system_schema.columns {0};'''.format(where_clause), } ret = {} try: ret = cql_query(query, contact_points, port, cql_user, cql_pass) except CommandExecutionError: log.critical('Could not list column families.') raise except BaseException as e: log.critical('Unexpected error while listing column families: %s', e) raise return ret def keyspace_exists(keyspace, contact_points=None, port=None, cql_user=None, cql_pass=None): ''' Check if a keyspace exists in a Cassandra cluster. :param keyspace The keyspace name to check for. :type keyspace: str :param contact_points: The Cassandra cluster addresses, can either be a string or a list of IPs. :type contact_points: str | list[str] :param cql_user: The Cassandra user if authentication is turned on. :type cql_user: str :param cql_pass: The Cassandra user password if authentication is turned on. :type cql_pass: str :param port: The Cassandra cluster port, defaults to None. :type port: int :return: The info for the keyspace or False if it does not exist. :rtype: dict CLI Example: .. code-block:: bash salt 'minion1' cassandra_cql.keyspace_exists keyspace=system ''' query = { '2': '''select keyspace_name from system.schema_keyspaces where keyspace_name = '{0}';'''.format(keyspace), '3': '''select keyspace_name from system_schema.keyspaces where keyspace_name = '{0}';'''.format(keyspace), } try: ret = cql_query(query, contact_points, port, cql_user, cql_pass) except CommandExecutionError: log.critical('Could not determine if keyspace exists.') raise except BaseException as e: log.critical('Unexpected error while determining if keyspace exists: %s', e) raise return True if ret else False def create_keyspace(keyspace, replication_strategy='SimpleStrategy', replication_factor=1, replication_datacenters=None, contact_points=None, port=None, cql_user=None, cql_pass=None): ''' Create a new keyspace in Cassandra. :param keyspace: The keyspace name :type keyspace: str :param replication_strategy: either `SimpleStrategy` or `NetworkTopologyStrategy` :type replication_strategy: str :param replication_factor: number of replicas of data on multiple nodes. not used if using NetworkTopologyStrategy :type replication_factor: int :param replication_datacenters: string or dict of datacenter names to replication factors, required if using NetworkTopologyStrategy (will be a dict if coming from state file). :type replication_datacenters: str | dict[str, int] :param contact_points: The Cassandra cluster addresses, can either be a string or a list of IPs. :type contact_points: str | list[str] :param cql_user: The Cassandra user if authentication is turned on. :type cql_user: str :param cql_pass: The Cassandra user password if authentication is turned on. :type cql_pass: str :param port: The Cassandra cluster port, defaults to None. :type port: int :return: The info for the keyspace or False if it does not exist. :rtype: dict CLI Example: .. code-block:: bash # CLI Example: salt 'minion1' cassandra_cql.create_keyspace keyspace=newkeyspace salt 'minion1' cassandra_cql.create_keyspace keyspace=newkeyspace replication_strategy=NetworkTopologyStrategy \ replication_datacenters='{"datacenter_1": 3, "datacenter_2": 2}' ''' existing_keyspace = keyspace_exists(keyspace, contact_points, port) if not existing_keyspace: # Add the strategy, replication_factor, etc. replication_map = { 'class': replication_strategy } if replication_datacenters: if isinstance(replication_datacenters, six.string_types): try: replication_datacenter_map = salt.utils.json.loads(replication_datacenters) replication_map.update(**replication_datacenter_map) except BaseException: # pylint: disable=W0703 log.error("Could not load json replication_datacenters.") return False else: replication_map.update(**replication_datacenters) else: replication_map['replication_factor'] = replication_factor query = '''create keyspace {0} with replication = {1} and durable_writes = true;'''.format(keyspace, replication_map) try: cql_query(query, contact_points, port, cql_user, cql_pass) except CommandExecutionError: log.critical('Could not create keyspace.') raise except BaseException as e: log.critical('Unexpected error while creating keyspace: %s', e) raise def drop_keyspace(keyspace, contact_points=None, port=None, cql_user=None, cql_pass=None): ''' Drop a keyspace if it exists in a Cassandra cluster. :param keyspace: The keyspace to drop. :type keyspace: str :param contact_points: The Cassandra cluster addresses, can either be a string or a list of IPs. :type contact_points: str | list[str] :param cql_user: The Cassandra user if authentication is turned on. :type cql_user: str :param cql_pass: The Cassandra user password if authentication is turned on. :type cql_pass: str :param port: The Cassandra cluster port, defaults to None. :type port: int :return: The info for the keyspace or False if it does not exist. :rtype: dict CLI Example: .. code-block:: bash salt 'minion1' cassandra_cql.drop_keyspace keyspace=test salt 'minion1' cassandra_cql.drop_keyspace keyspace=test contact_points=minion1 ''' existing_keyspace = keyspace_exists(keyspace, contact_points, port) if existing_keyspace: query = '''drop keyspace {0};'''.format(keyspace) try: cql_query(query, contact_points, port, cql_user, cql_pass) except CommandExecutionError: log.critical('Could not drop keyspace.') raise except BaseException as e: log.critical('Unexpected error while dropping keyspace: %s', e) raise return True def list_users(contact_points=None, port=None, cql_user=None, cql_pass=None): ''' List existing users in this Cassandra cluster. :param contact_points: The Cassandra cluster addresses, can either be a string or a list of IPs. :type contact_points: str | list[str] :param port: The Cassandra cluster port, defaults to None. :type port: int :param cql_user: The Cassandra user if authentication is turned on. :type cql_user: str :param cql_pass: The Cassandra user password if authentication is turned on. :type cql_pass: str :return: The list of existing users. :rtype: dict CLI Example: .. code-block:: bash salt 'minion1' cassandra_cql.list_users salt 'minion1' cassandra_cql.list_users contact_points=minion1 ''' query = "list users;" ret = {} try: ret = cql_query(query, contact_points, port, cql_user, cql_pass) except CommandExecutionError: log.critical('Could not list users.') raise except BaseException as e: log.critical('Unexpected error while listing users: %s', e) raise return ret def create_user(username, password, superuser=False, contact_points=None, port=None, cql_user=None, cql_pass=None): ''' Create a new cassandra user with credentials and superuser status. :param username: The name of the new user. :type username: str :param password: The password of the new user. :type password: str :param superuser: Is the new user going to be a superuser? default: False :type superuser: bool :param contact_points: The Cassandra cluster addresses, can either be a string or a list of IPs. :type contact_points: str | list[str] :param cql_user: The Cassandra user if authentication is turned on. :type cql_user: str :param cql_pass: The Cassandra user password if authentication is turned on. :type cql_pass: str :param port: The Cassandra cluster port, defaults to None. :type port: int :return: :rtype: CLI Example: .. code-block:: bash salt 'minion1' cassandra_cql.create_user username=joe password=secret salt 'minion1' cassandra_cql.create_user username=joe password=secret superuser=True salt 'minion1' cassandra_cql.create_user username=joe password=secret superuser=True contact_points=minion1 ''' superuser_cql = 'superuser' if superuser else 'nosuperuser' query = '''create user if not exists {0} with password '{1}' {2};'''.format(username, password, superuser_cql) log.debug("Attempting to create a new user with username=%s superuser=%s", username, superuser_cql) # The create user query doesn't actually return anything if the query succeeds. # If the query fails, catch the exception, log a messange and raise it again. try: cql_query(query, contact_points, port, cql_user, cql_pass) except CommandExecutionError: log.critical('Could not create user.') raise except BaseException as e: log.critical('Unexpected error while creating user: %s', e) raise return True def create_role(username, password, superuser=False, login=False, contact_points=None, port=None, cql_user=None, cql_pass=None): ''' Create a new cassandra role with credentials and superuser status. :param username: The name of the new user. :type username: str :param password: The password of the new user. :type password: str :param superuser: Is the new role going to be a superuser? default: False :type superuser: bool :param login: Is the new role going to be allowed to log in? default: False :type superuser: bool :param contact_points: The Cassandra cluster addresses, can either be a string or a list of IPs. :type contact_points: str | list[str] :param cql_user: The Cassandra user if authentication is turned on. :type cql_user: str :param cql_pass: The Cassandra user password if authentication is turned on. :type cql_pass: str :param port: The Cassandra cluster port, defaults to None. :type port: int :return: :rtype: CLI Example: .. code-block:: bash salt 'minion1' cassandra_cql.create_role username=joe password=secret salt 'minion1' cassandra_cql.create_role username=joe password=secret superuser=True salt 'minion1' cassandra_cql.create_role username=joe password=secret superuser=True login=True salt 'minion1' cassandra_cql.create_role username=joe password=secret superuser=True login=True contact_points=minion1 ''' superuser_cql = 'superuser = true' if superuser else 'superuser = false' login_cql = 'login = true' if login else 'login = false' query = '''create role if not exists {0} with password '{1}' and {2} and {3} ;'''.format(username, password, superuser_cql, login_cql) log.debug("Attempting to create a new role with username=%s superuser=%s login=%s", username, superuser, login) # The create role query doesn't actually return anything if the query succeeds. # If the query fails, catch the exception, log a messange and raise it again. try: cql_query(query, contact_points, port, cql_user, cql_pass) except CommandExecutionError: log.critical('Could not create role.') raise except BaseException as e: log.critical('Unexpected error while creating role: %s', e) raise return True def list_permissions(username=None, resource=None, resource_type='keyspace', permission=None, contact_points=None, port=None, cql_user=None, cql_pass=None): ''' List permissions. :param username: The name of the user to list permissions for. :type username: str :param resource: The resource (keyspace or table), if None, permissions for all resources are listed. :type resource: str :param resource_type: The resource_type (keyspace or table), defaults to 'keyspace'. :type resource_type: str :param permission: A permission name (e.g. select), if None, all permissions are listed. :type permission: str :param contact_points: The Cassandra cluster addresses, can either be a string or a list of IPs. :type contact_points: str | list[str] :param cql_user: The Cassandra user if authentication is turned on. :type cql_user: str :param cql_pass: The Cassandra user password if authentication is turned on. :type cql_pass: str :param port: The Cassandra cluster port, defaults to None. :type port: int :return: Dictionary of permissions. :rtype: dict CLI Example: .. code-block:: bash salt 'minion1' cassandra_cql.list_permissions salt 'minion1' cassandra_cql.list_permissions username=joe resource=test_keyspace permission=select salt 'minion1' cassandra_cql.list_permissions username=joe resource=test_table resource_type=table \ permission=select contact_points=minion1 ''' keyspace_cql = "{0} {1}".format(resource_type, resource) if resource else "all keyspaces" permission_cql = "{0} permission".format(permission) if permission else "all permissions" query = "list {0} on {1}".format(permission_cql, keyspace_cql) if username: query = "{0} of {1}".format(query, username) log.debug("Attempting to list permissions with query '%s'", query) ret = {} try: ret = cql_query(query, contact_points, port, cql_user, cql_pass) except CommandExecutionError: log.critical('Could not list permissions.') raise except BaseException as e: log.critical('Unexpected error while listing permissions: %s', e) raise return ret def grant_permission(username, resource=None, resource_type='keyspace', permission=None, contact_points=None, port=None, cql_user=None, cql_pass=None): ''' Grant permissions to a user. :param username: The name of the user to grant permissions to. :type username: str :param resource: The resource (keyspace or table), if None, permissions for all resources are granted. :type resource: str :param resource_type: The resource_type (keyspace or table), defaults to 'keyspace'. :type resource_type: str :param permission: A permission name (e.g. select), if None, all permissions are granted. :type permission: str :param contact_points: The Cassandra cluster addresses, can either be a string or a list of IPs. :type contact_points: str | list[str] :param cql_user: The Cassandra user if authentication is turned on. :type cql_user: str :param cql_pass: The Cassandra user password if authentication is turned on. :type cql_pass: str :param port: The Cassandra cluster port, defaults to None. :type port: int :return: :rtype: CLI Example: .. code-block:: bash salt 'minion1' cassandra_cql.grant_permission salt 'minion1' cassandra_cql.grant_permission username=joe resource=test_keyspace permission=select salt 'minion1' cassandra_cql.grant_permission username=joe resource=test_table resource_type=table \ permission=select contact_points=minion1 ''' permission_cql = "grant {0}".format(permission) if permission else "grant all permissions" resource_cql = "on {0} {1}".format(resource_type, resource) if resource else "on all keyspaces" query = "{0} {1} to {2}".format(permission_cql, resource_cql, username) log.debug("Attempting to grant permissions with query '%s'", query) try: cql_query(query, contact_points, port, cql_user, cql_pass) except CommandExecutionError: log.critical('Could not grant permissions.') raise except BaseException as e: log.critical('Unexpected error while granting permissions: %s', e) raise return True
saltstack/salt
salt/modules/cassandra_cql.py
list_column_families
python
def list_column_families(keyspace=None, contact_points=None, port=None, cql_user=None, cql_pass=None): ''' List column families in a Cassandra cluster for all keyspaces or just the provided one. :param keyspace: The keyspace to provide the column families for, optional. :type keyspace: str :param contact_points: The Cassandra cluster addresses, can either be a string or a list of IPs. :type contact_points: str | list[str] :param cql_user: The Cassandra user if authentication is turned on. :type cql_user: str :param cql_pass: The Cassandra user password if authentication is turned on. :type cql_pass: str :param port: The Cassandra cluster port, defaults to None. :type port: int :return: The column families in this Cassandra cluster. :rtype: list[dict] CLI Example: .. code-block:: bash salt 'minion1' cassandra_cql.list_column_families salt 'minion1' cassandra_cql.list_column_families contact_points=minion1 salt 'minion1' cassandra_cql.list_column_families keyspace=system ''' where_clause = "where keyspace_name = '{0}'".format(keyspace) if keyspace else "" query = { '2': '''select columnfamily_name from system.schema_columnfamilies {0};'''.format(where_clause), '3': '''select column_name from system_schema.columns {0};'''.format(where_clause), } ret = {} try: ret = cql_query(query, contact_points, port, cql_user, cql_pass) except CommandExecutionError: log.critical('Could not list column families.') raise except BaseException as e: log.critical('Unexpected error while listing column families: %s', e) raise return ret
List column families in a Cassandra cluster for all keyspaces or just the provided one. :param keyspace: The keyspace to provide the column families for, optional. :type keyspace: str :param contact_points: The Cassandra cluster addresses, can either be a string or a list of IPs. :type contact_points: str | list[str] :param cql_user: The Cassandra user if authentication is turned on. :type cql_user: str :param cql_pass: The Cassandra user password if authentication is turned on. :type cql_pass: str :param port: The Cassandra cluster port, defaults to None. :type port: int :return: The column families in this Cassandra cluster. :rtype: list[dict] CLI Example: .. code-block:: bash salt 'minion1' cassandra_cql.list_column_families salt 'minion1' cassandra_cql.list_column_families contact_points=minion1 salt 'minion1' cassandra_cql.list_column_families keyspace=system
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/cassandra_cql.py#L596-L643
[ "def cql_query(query, contact_points=None, port=None, cql_user=None, cql_pass=None):\n '''\n Run a query on a Cassandra cluster and return a dictionary.\n\n :param query: The query to execute.\n :type query: str\n :param contact_points: The Cassandra cluster addresses, can either be a string or a list of IPs.\n :type contact_points: str | list[str]\n :param cql_user: The Cassandra user if authentication is turned on.\n :type cql_user: str\n :param cql_pass: The Cassandra user password if authentication is turned on.\n :type cql_pass: str\n :param port: The Cassandra cluster port, defaults to None.\n :type port: int\n :param params: The parameters for the query, optional.\n :type params: str\n :return: A dictionary from the return values of the query\n :rtype: list[dict]\n\n CLI Example:\n\n .. code-block:: bash\n\n salt 'cassandra-server' cassandra_cql.cql_query \"SELECT * FROM users_by_name WHERE first_name = 'jane'\"\n '''\n try:\n cluster, session = _connect(contact_points=contact_points, port=port, cql_user=cql_user, cql_pass=cql_pass)\n except CommandExecutionError:\n log.critical('Could not get Cassandra cluster session.')\n raise\n except BaseException as e:\n log.critical('Unexpected error while getting Cassandra cluster session: %s', e)\n raise\n\n session.row_factory = dict_factory\n ret = []\n\n # Cassandra changed their internal schema from v2 to v3\n # If the query contains a dictionary sorted by versions\n # Find the query for the current cluster version.\n # https://issues.apache.org/jira/browse/CASSANDRA-6717\n if isinstance(query, dict):\n cluster_version = version(contact_points=contact_points,\n port=port,\n cql_user=cql_user,\n cql_pass=cql_pass)\n match = re.match(r'^(\\d+)\\.(\\d+)(?:\\.(\\d+))?', cluster_version)\n major, minor, point = match.groups()\n # try to find the specific version in the query dictionary\n # then try the major version\n # otherwise default to the highest version number\n try:\n query = query[cluster_version]\n except KeyError:\n query = query.get(major, max(query))\n log.debug('New query is: %s', query)\n\n try:\n results = session.execute(query)\n except BaseException as e:\n log.error('Failed to execute query: %s\\n reason: %s', query, e)\n msg = \"ERROR: Cassandra query failed: {0} reason: {1}\".format(query, e)\n raise CommandExecutionError(msg)\n\n if results:\n for result in results:\n values = {}\n for key, value in six.iteritems(result):\n # Salt won't return dictionaries with odd types like uuid.UUID\n if not isinstance(value, six.text_type):\n # Must support Cassandra collection types.\n # Namely, Cassandras set, list, and map collections.\n if not isinstance(value, (set, list, dict)):\n value = six.text_type(value)\n values[key] = value\n ret.append(values)\n\n return ret\n" ]
# -*- coding: utf-8 -*- ''' Cassandra Database Module .. versionadded:: 2015.5.0 This module works with Cassandra v2 and v3 and hence generates queries based on the internal schema of said version. :depends: DataStax Python Driver for Apache Cassandra https://github.com/datastax/python-driver pip install cassandra-driver :referenced by: Salt's cassandra_cql returner :configuration: The Cassandra cluster members and connection port can either be specified in the master or minion config, the minion's pillar or be passed to the module. Example configuration in the config for a single node: .. code-block:: yaml cassandra: cluster: 192.168.50.10 port: 9000 Example configuration in the config for a cluster: .. code-block:: yaml cassandra: cluster: - 192.168.50.10 - 192.168.50.11 - 192.168.50.12 port: 9000 username: cas_admin .. versionchanged:: 2016.11.0 Added support for ``ssl_options`` and ``protocol_version``. Example configuration with `ssl options <http://datastax.github.io/python-driver/api/cassandra/cluster.html#cassandra.cluster.Cluster.ssl_options>`_: If ``ssl_options`` are present in cassandra config the cassandra_cql returner will use SSL. SSL isn't used if ``ssl_options`` isn't specified. .. code-block:: yaml cassandra: cluster: - 192.168.50.10 - 192.168.50.11 - 192.168.50.12 port: 9000 username: cas_admin ssl_options: ca_certs: /etc/ssl/certs/ca-bundle.trust.crt # SSL version should be one from the ssl module # This is an optional parameter ssl_version: PROTOCOL_TLSv1 Additionally you can also specify the ``protocol_version`` to `use <http://datastax.github.io/python-driver/api/cassandra/cluster.html#cassandra.cluster.Cluster.ssl_options>`_. .. code-block:: yaml cassandra: cluster: - 192.168.50.10 - 192.168.50.11 - 192.168.50.12 port: 9000 username: cas_admin # defaults to 4, if not set protocol_version: 3 ''' # Import Python Libs from __future__ import absolute_import, unicode_literals, print_function import logging import re import ssl # Import Salt Libs import salt.utils.json from salt.exceptions import CommandExecutionError # Import 3rd-party libs from salt.ext import six from salt.ext.six.moves import range import salt.utils.versions SSL_VERSION = 'ssl_version' log = logging.getLogger(__name__) __virtualname__ = 'cassandra_cql' HAS_DRIVER = False try: # pylint: disable=import-error,no-name-in-module from cassandra.cluster import Cluster from cassandra.cluster import NoHostAvailable from cassandra.connection import ConnectionException, \ ConnectionShutdown, OperationTimedOut from cassandra.auth import PlainTextAuthProvider from cassandra.query import dict_factory # pylint: enable=import-error,no-name-in-module HAS_DRIVER = True except ImportError: pass def __virtual__(): ''' Return virtual name of the module only if the python driver can be loaded. :return: The virtual name of the module. :rtype: str ''' if HAS_DRIVER: return __virtualname__ return (False, 'Cannot load cassandra_cql module: python driver not found') def _async_log_errors(errors): log.error('Cassandra_cql asynchronous call returned: %s', errors) def _load_properties(property_name, config_option, set_default=False, default=None): ''' Load properties for the cassandra module from config or pillar. :param property_name: The property to load. :type property_name: str or list of str :param config_option: The name of the config option. :type config_option: str :param set_default: Should a default be set if not found in config. :type set_default: bool :param default: The default value to be set. :type default: str or int :return: The property fetched from the configuration or default. :rtype: str or list of str ''' if not property_name: log.debug("No property specified in function, trying to load from salt configuration") try: options = __salt__['config.option']('cassandra') except BaseException as e: log.error("Failed to get cassandra config options. Reason: %s", e) raise loaded_property = options.get(config_option) if not loaded_property: if set_default: log.debug('Setting default Cassandra %s to %s', config_option, default) loaded_property = default else: log.error('No cassandra %s specified in the configuration or passed to the module.', config_option) raise CommandExecutionError("ERROR: Cassandra {0} cannot be empty.".format(config_option)) return loaded_property return property_name def _get_ssl_opts(): ''' Parse out ssl_options for Cassandra cluster connection. Make sure that the ssl_version (if any specified) is valid. ''' sslopts = __salt__['config.option']('cassandra').get('ssl_options', None) ssl_opts = {} if sslopts: ssl_opts['ca_certs'] = sslopts['ca_certs'] if SSL_VERSION in sslopts: if not sslopts[SSL_VERSION].startswith('PROTOCOL_'): valid_opts = ', '.join( [x for x in dir(ssl) if x.startswith('PROTOCOL_')] ) raise CommandExecutionError('Invalid protocol_version ' 'specified! ' 'Please make sure ' 'that the ssl protocol' 'version is one from the SSL' 'module. ' 'Valid options are ' '{0}'.format(valid_opts)) else: ssl_opts[SSL_VERSION] = \ getattr(ssl, sslopts[SSL_VERSION]) return ssl_opts else: return None def _connect(contact_points=None, port=None, cql_user=None, cql_pass=None, protocol_version=None): ''' Connect to a Cassandra cluster. :param contact_points: The Cassandra cluster addresses, can either be a string or a list of IPs. :type contact_points: str or list of str :param cql_user: The Cassandra user if authentication is turned on. :type cql_user: str :param cql_pass: The Cassandra user password if authentication is turned on. :type cql_pass: str :param port: The Cassandra cluster port, defaults to None. :type port: int :param protocol_version: Cassandra protocol version to use. :type port: int :return: The session and cluster objects. :rtype: cluster object, session object ''' # Lazy load the Cassandra cluster and session for this module by creating a # cluster and session when cql_query is called the first time. Get the # Cassandra cluster and session from this module's __context__ after it is # loaded the first time cql_query is called. # # TODO: Call cluster.shutdown() when the module is unloaded on # master/minion shutdown. Currently, Master.shutdown() and Minion.shutdown() # do nothing to allow loaded modules to gracefully handle resources stored # in __context__ (i.e. connection pools). This means that the connection # pool is orphaned and Salt relies on Cassandra to reclaim connections. # Perhaps if Master/Minion daemons could be enhanced to call an "__unload__" # function, or something similar for each loaded module, connection pools # and the like can be gracefully reclaimed/shutdown. if (__context__ and 'cassandra_cql_returner_cluster' in __context__ and 'cassandra_cql_returner_session' in __context__): return __context__['cassandra_cql_returner_cluster'], __context__['cassandra_cql_returner_session'] else: contact_points = _load_properties(property_name=contact_points, config_option='cluster') contact_points = contact_points if isinstance(contact_points, list) else contact_points.split(',') port = _load_properties(property_name=port, config_option='port', set_default=True, default=9042) cql_user = _load_properties(property_name=cql_user, config_option='username', set_default=True, default="cassandra") cql_pass = _load_properties(property_name=cql_pass, config_option='password', set_default=True, default="cassandra") protocol_version = _load_properties(property_name=protocol_version, config_option='protocol_version', set_default=True, default=4) try: auth_provider = PlainTextAuthProvider(username=cql_user, password=cql_pass) ssl_opts = _get_ssl_opts() if ssl_opts: cluster = Cluster(contact_points, port=port, auth_provider=auth_provider, ssl_options=ssl_opts, protocol_version=protocol_version, compression=True) else: cluster = Cluster(contact_points, port=port, auth_provider=auth_provider, protocol_version=protocol_version, compression=True) for recontimes in range(1, 4): try: session = cluster.connect() break except OperationTimedOut: log.warning('Cassandra cluster.connect timed out, try %s', recontimes) if recontimes >= 3: raise # TODO: Call cluster.shutdown() when the module is unloaded on shutdown. __context__['cassandra_cql_returner_cluster'] = cluster __context__['cassandra_cql_returner_session'] = session __context__['cassandra_cql_prepared'] = {} log.debug('Successfully connected to Cassandra cluster at %s', contact_points) return cluster, session except TypeError: pass except (ConnectionException, ConnectionShutdown, NoHostAvailable): log.error('Could not connect to Cassandra cluster at %s', contact_points) raise CommandExecutionError('ERROR: Could not connect to Cassandra cluster.') def cql_query(query, contact_points=None, port=None, cql_user=None, cql_pass=None): ''' Run a query on a Cassandra cluster and return a dictionary. :param query: The query to execute. :type query: str :param contact_points: The Cassandra cluster addresses, can either be a string or a list of IPs. :type contact_points: str | list[str] :param cql_user: The Cassandra user if authentication is turned on. :type cql_user: str :param cql_pass: The Cassandra user password if authentication is turned on. :type cql_pass: str :param port: The Cassandra cluster port, defaults to None. :type port: int :param params: The parameters for the query, optional. :type params: str :return: A dictionary from the return values of the query :rtype: list[dict] CLI Example: .. code-block:: bash salt 'cassandra-server' cassandra_cql.cql_query "SELECT * FROM users_by_name WHERE first_name = 'jane'" ''' try: cluster, session = _connect(contact_points=contact_points, port=port, cql_user=cql_user, cql_pass=cql_pass) except CommandExecutionError: log.critical('Could not get Cassandra cluster session.') raise except BaseException as e: log.critical('Unexpected error while getting Cassandra cluster session: %s', e) raise session.row_factory = dict_factory ret = [] # Cassandra changed their internal schema from v2 to v3 # If the query contains a dictionary sorted by versions # Find the query for the current cluster version. # https://issues.apache.org/jira/browse/CASSANDRA-6717 if isinstance(query, dict): cluster_version = version(contact_points=contact_points, port=port, cql_user=cql_user, cql_pass=cql_pass) match = re.match(r'^(\d+)\.(\d+)(?:\.(\d+))?', cluster_version) major, minor, point = match.groups() # try to find the specific version in the query dictionary # then try the major version # otherwise default to the highest version number try: query = query[cluster_version] except KeyError: query = query.get(major, max(query)) log.debug('New query is: %s', query) try: results = session.execute(query) except BaseException as e: log.error('Failed to execute query: %s\n reason: %s', query, e) msg = "ERROR: Cassandra query failed: {0} reason: {1}".format(query, e) raise CommandExecutionError(msg) if results: for result in results: values = {} for key, value in six.iteritems(result): # Salt won't return dictionaries with odd types like uuid.UUID if not isinstance(value, six.text_type): # Must support Cassandra collection types. # Namely, Cassandras set, list, and map collections. if not isinstance(value, (set, list, dict)): value = six.text_type(value) values[key] = value ret.append(values) return ret def cql_query_with_prepare(query, statement_name, statement_arguments, callback_errors=None, contact_points=None, port=None, cql_user=None, cql_pass=None, **kwargs): ''' Run a query on a Cassandra cluster and return a dictionary. This function should not be used asynchronously for SELECTs -- it will not return anything and we don't currently have a mechanism for handling a future that will return results. :param query: The query to execute. :type query: str :param statement_name: Name to assign the prepared statement in the __context__ dictionary :type statement_name: str :param statement_arguments: Bind parameters for the SQL statement :type statement_arguments: list[str] :param async: Run this query in asynchronous mode :type async: bool :param callback_errors: Function to call after query runs if there is an error :type callback_errors: Function callable :param contact_points: The Cassandra cluster addresses, can either be a string or a list of IPs. :type contact_points: str | list[str] :param cql_user: The Cassandra user if authentication is turned on. :type cql_user: str :param cql_pass: The Cassandra user password if authentication is turned on. :type cql_pass: str :param port: The Cassandra cluster port, defaults to None. :type port: int :param params: The parameters for the query, optional. :type params: str :return: A dictionary from the return values of the query :rtype: list[dict] CLI Example: .. code-block:: bash # Insert data asynchronously salt this-node cassandra_cql.cql_query_with_prepare "name_insert" "INSERT INTO USERS (first_name, last_name) VALUES (?, ?)" \ statement_arguments=['John','Doe'], asynchronous=True # Select data, should not be asynchronous because there is not currently a facility to return data from a future salt this-node cassandra_cql.cql_query_with_prepare "name_select" "SELECT * FROM USERS WHERE first_name=?" \ statement_arguments=['John'] ''' # Backward-compatibility with Python 3.7: "async" is a reserved word asynchronous = kwargs.get('async', False) try: cluster, session = _connect(contact_points=contact_points, port=port, cql_user=cql_user, cql_pass=cql_pass) except CommandExecutionError: log.critical('Could not get Cassandra cluster session.') raise except BaseException as e: log.critical('Unexpected error while getting Cassandra cluster session: %s', e) raise if statement_name not in __context__['cassandra_cql_prepared']: try: bound_statement = session.prepare(query) __context__['cassandra_cql_prepared'][statement_name] = bound_statement except BaseException as e: log.critical('Unexpected error while preparing SQL statement: %s', e) raise else: bound_statement = __context__['cassandra_cql_prepared'][statement_name] session.row_factory = dict_factory ret = [] try: if asynchronous: future_results = session.execute_async(bound_statement.bind(statement_arguments)) # future_results.add_callbacks(_async_log_errors) else: results = session.execute(bound_statement.bind(statement_arguments)) except BaseException as e: log.error('Failed to execute query: %s\n reason: %s', query, e) msg = "ERROR: Cassandra query failed: {0} reason: {1}".format(query, e) raise CommandExecutionError(msg) if not asynchronous and results: for result in results: values = {} for key, value in six.iteritems(result): # Salt won't return dictionaries with odd types like uuid.UUID if not isinstance(value, six.text_type): # Must support Cassandra collection types. # Namely, Cassandras set, list, and map collections. if not isinstance(value, (set, list, dict)): value = six.text_type(value) values[key] = value ret.append(values) # If this was a synchronous call, then we either have an empty list # because there was no return, or we have a return # If this was an asynchronous call we only return the empty list return ret def version(contact_points=None, port=None, cql_user=None, cql_pass=None): ''' Show the Cassandra version. :param contact_points: The Cassandra cluster addresses, can either be a string or a list of IPs. :type contact_points: str | list[str] :param cql_user: The Cassandra user if authentication is turned on. :type cql_user: str :param cql_pass: The Cassandra user password if authentication is turned on. :type cql_pass: str :param port: The Cassandra cluster port, defaults to None. :type port: int :return: The version for this Cassandra cluster. :rtype: str CLI Example: .. code-block:: bash salt 'minion1' cassandra_cql.version salt 'minion1' cassandra_cql.version contact_points=minion1 ''' query = '''select release_version from system.local limit 1;''' try: ret = cql_query(query, contact_points, port, cql_user, cql_pass) except CommandExecutionError: log.critical('Could not get Cassandra version.') raise except BaseException as e: log.critical('Unexpected error while getting Cassandra version: %s', e) raise return ret[0].get('release_version') def info(contact_points=None, port=None, cql_user=None, cql_pass=None): ''' Show the Cassandra information for this cluster. :param contact_points: The Cassandra cluster addresses, can either be a string or a list of IPs. :type contact_points: str | list[str] :param cql_user: The Cassandra user if authentication is turned on. :type cql_user: str :param cql_pass: The Cassandra user password if authentication is turned on. :type cql_pass: str :param port: The Cassandra cluster port, defaults to None. :type port: int :return: The information for this Cassandra cluster. :rtype: dict CLI Example: .. code-block:: bash salt 'minion1' cassandra_cql.info salt 'minion1' cassandra_cql.info contact_points=minion1 ''' query = '''select cluster_name, data_center, partitioner, host_id, rack, release_version, cql_version, schema_version, thrift_version from system.local limit 1;''' ret = {} try: ret = cql_query(query, contact_points, port, cql_user, cql_pass) except CommandExecutionError: log.critical('Could not list Cassandra info.') raise except BaseException as e: log.critical('Unexpected error while listing Cassandra info: %s', e) raise return ret def list_keyspaces(contact_points=None, port=None, cql_user=None, cql_pass=None): ''' List keyspaces in a Cassandra cluster. :param contact_points: The Cassandra cluster addresses, can either be a string or a list of IPs. :type contact_points: str | list[str] :param cql_user: The Cassandra user if authentication is turned on. :type cql_user: str :param cql_pass: The Cassandra user password if authentication is turned on. :type cql_pass: str :param port: The Cassandra cluster port, defaults to None. :type port: int :return: The keyspaces in this Cassandra cluster. :rtype: list[dict] CLI Example: .. code-block:: bash salt 'minion1' cassandra_cql.list_keyspaces salt 'minion1' cassandra_cql.list_keyspaces contact_points=minion1 port=9000 ''' query = { '2': 'select keyspace_name from system.schema_keyspaces;', '3': 'select keyspace_name from system_schema.keyspaces;', } ret = {} try: ret = cql_query(query, contact_points, port, cql_user, cql_pass) except CommandExecutionError: log.critical('Could not list keyspaces.') raise except BaseException as e: log.critical('Unexpected error while listing keyspaces: %s', e) raise return ret def keyspace_exists(keyspace, contact_points=None, port=None, cql_user=None, cql_pass=None): ''' Check if a keyspace exists in a Cassandra cluster. :param keyspace The keyspace name to check for. :type keyspace: str :param contact_points: The Cassandra cluster addresses, can either be a string or a list of IPs. :type contact_points: str | list[str] :param cql_user: The Cassandra user if authentication is turned on. :type cql_user: str :param cql_pass: The Cassandra user password if authentication is turned on. :type cql_pass: str :param port: The Cassandra cluster port, defaults to None. :type port: int :return: The info for the keyspace or False if it does not exist. :rtype: dict CLI Example: .. code-block:: bash salt 'minion1' cassandra_cql.keyspace_exists keyspace=system ''' query = { '2': '''select keyspace_name from system.schema_keyspaces where keyspace_name = '{0}';'''.format(keyspace), '3': '''select keyspace_name from system_schema.keyspaces where keyspace_name = '{0}';'''.format(keyspace), } try: ret = cql_query(query, contact_points, port, cql_user, cql_pass) except CommandExecutionError: log.critical('Could not determine if keyspace exists.') raise except BaseException as e: log.critical('Unexpected error while determining if keyspace exists: %s', e) raise return True if ret else False def create_keyspace(keyspace, replication_strategy='SimpleStrategy', replication_factor=1, replication_datacenters=None, contact_points=None, port=None, cql_user=None, cql_pass=None): ''' Create a new keyspace in Cassandra. :param keyspace: The keyspace name :type keyspace: str :param replication_strategy: either `SimpleStrategy` or `NetworkTopologyStrategy` :type replication_strategy: str :param replication_factor: number of replicas of data on multiple nodes. not used if using NetworkTopologyStrategy :type replication_factor: int :param replication_datacenters: string or dict of datacenter names to replication factors, required if using NetworkTopologyStrategy (will be a dict if coming from state file). :type replication_datacenters: str | dict[str, int] :param contact_points: The Cassandra cluster addresses, can either be a string or a list of IPs. :type contact_points: str | list[str] :param cql_user: The Cassandra user if authentication is turned on. :type cql_user: str :param cql_pass: The Cassandra user password if authentication is turned on. :type cql_pass: str :param port: The Cassandra cluster port, defaults to None. :type port: int :return: The info for the keyspace or False if it does not exist. :rtype: dict CLI Example: .. code-block:: bash # CLI Example: salt 'minion1' cassandra_cql.create_keyspace keyspace=newkeyspace salt 'minion1' cassandra_cql.create_keyspace keyspace=newkeyspace replication_strategy=NetworkTopologyStrategy \ replication_datacenters='{"datacenter_1": 3, "datacenter_2": 2}' ''' existing_keyspace = keyspace_exists(keyspace, contact_points, port) if not existing_keyspace: # Add the strategy, replication_factor, etc. replication_map = { 'class': replication_strategy } if replication_datacenters: if isinstance(replication_datacenters, six.string_types): try: replication_datacenter_map = salt.utils.json.loads(replication_datacenters) replication_map.update(**replication_datacenter_map) except BaseException: # pylint: disable=W0703 log.error("Could not load json replication_datacenters.") return False else: replication_map.update(**replication_datacenters) else: replication_map['replication_factor'] = replication_factor query = '''create keyspace {0} with replication = {1} and durable_writes = true;'''.format(keyspace, replication_map) try: cql_query(query, contact_points, port, cql_user, cql_pass) except CommandExecutionError: log.critical('Could not create keyspace.') raise except BaseException as e: log.critical('Unexpected error while creating keyspace: %s', e) raise def drop_keyspace(keyspace, contact_points=None, port=None, cql_user=None, cql_pass=None): ''' Drop a keyspace if it exists in a Cassandra cluster. :param keyspace: The keyspace to drop. :type keyspace: str :param contact_points: The Cassandra cluster addresses, can either be a string or a list of IPs. :type contact_points: str | list[str] :param cql_user: The Cassandra user if authentication is turned on. :type cql_user: str :param cql_pass: The Cassandra user password if authentication is turned on. :type cql_pass: str :param port: The Cassandra cluster port, defaults to None. :type port: int :return: The info for the keyspace or False if it does not exist. :rtype: dict CLI Example: .. code-block:: bash salt 'minion1' cassandra_cql.drop_keyspace keyspace=test salt 'minion1' cassandra_cql.drop_keyspace keyspace=test contact_points=minion1 ''' existing_keyspace = keyspace_exists(keyspace, contact_points, port) if existing_keyspace: query = '''drop keyspace {0};'''.format(keyspace) try: cql_query(query, contact_points, port, cql_user, cql_pass) except CommandExecutionError: log.critical('Could not drop keyspace.') raise except BaseException as e: log.critical('Unexpected error while dropping keyspace: %s', e) raise return True def list_users(contact_points=None, port=None, cql_user=None, cql_pass=None): ''' List existing users in this Cassandra cluster. :param contact_points: The Cassandra cluster addresses, can either be a string or a list of IPs. :type contact_points: str | list[str] :param port: The Cassandra cluster port, defaults to None. :type port: int :param cql_user: The Cassandra user if authentication is turned on. :type cql_user: str :param cql_pass: The Cassandra user password if authentication is turned on. :type cql_pass: str :return: The list of existing users. :rtype: dict CLI Example: .. code-block:: bash salt 'minion1' cassandra_cql.list_users salt 'minion1' cassandra_cql.list_users contact_points=minion1 ''' query = "list users;" ret = {} try: ret = cql_query(query, contact_points, port, cql_user, cql_pass) except CommandExecutionError: log.critical('Could not list users.') raise except BaseException as e: log.critical('Unexpected error while listing users: %s', e) raise return ret def create_user(username, password, superuser=False, contact_points=None, port=None, cql_user=None, cql_pass=None): ''' Create a new cassandra user with credentials and superuser status. :param username: The name of the new user. :type username: str :param password: The password of the new user. :type password: str :param superuser: Is the new user going to be a superuser? default: False :type superuser: bool :param contact_points: The Cassandra cluster addresses, can either be a string or a list of IPs. :type contact_points: str | list[str] :param cql_user: The Cassandra user if authentication is turned on. :type cql_user: str :param cql_pass: The Cassandra user password if authentication is turned on. :type cql_pass: str :param port: The Cassandra cluster port, defaults to None. :type port: int :return: :rtype: CLI Example: .. code-block:: bash salt 'minion1' cassandra_cql.create_user username=joe password=secret salt 'minion1' cassandra_cql.create_user username=joe password=secret superuser=True salt 'minion1' cassandra_cql.create_user username=joe password=secret superuser=True contact_points=minion1 ''' superuser_cql = 'superuser' if superuser else 'nosuperuser' query = '''create user if not exists {0} with password '{1}' {2};'''.format(username, password, superuser_cql) log.debug("Attempting to create a new user with username=%s superuser=%s", username, superuser_cql) # The create user query doesn't actually return anything if the query succeeds. # If the query fails, catch the exception, log a messange and raise it again. try: cql_query(query, contact_points, port, cql_user, cql_pass) except CommandExecutionError: log.critical('Could not create user.') raise except BaseException as e: log.critical('Unexpected error while creating user: %s', e) raise return True def create_role(username, password, superuser=False, login=False, contact_points=None, port=None, cql_user=None, cql_pass=None): ''' Create a new cassandra role with credentials and superuser status. :param username: The name of the new user. :type username: str :param password: The password of the new user. :type password: str :param superuser: Is the new role going to be a superuser? default: False :type superuser: bool :param login: Is the new role going to be allowed to log in? default: False :type superuser: bool :param contact_points: The Cassandra cluster addresses, can either be a string or a list of IPs. :type contact_points: str | list[str] :param cql_user: The Cassandra user if authentication is turned on. :type cql_user: str :param cql_pass: The Cassandra user password if authentication is turned on. :type cql_pass: str :param port: The Cassandra cluster port, defaults to None. :type port: int :return: :rtype: CLI Example: .. code-block:: bash salt 'minion1' cassandra_cql.create_role username=joe password=secret salt 'minion1' cassandra_cql.create_role username=joe password=secret superuser=True salt 'minion1' cassandra_cql.create_role username=joe password=secret superuser=True login=True salt 'minion1' cassandra_cql.create_role username=joe password=secret superuser=True login=True contact_points=minion1 ''' superuser_cql = 'superuser = true' if superuser else 'superuser = false' login_cql = 'login = true' if login else 'login = false' query = '''create role if not exists {0} with password '{1}' and {2} and {3} ;'''.format(username, password, superuser_cql, login_cql) log.debug("Attempting to create a new role with username=%s superuser=%s login=%s", username, superuser, login) # The create role query doesn't actually return anything if the query succeeds. # If the query fails, catch the exception, log a messange and raise it again. try: cql_query(query, contact_points, port, cql_user, cql_pass) except CommandExecutionError: log.critical('Could not create role.') raise except BaseException as e: log.critical('Unexpected error while creating role: %s', e) raise return True def list_permissions(username=None, resource=None, resource_type='keyspace', permission=None, contact_points=None, port=None, cql_user=None, cql_pass=None): ''' List permissions. :param username: The name of the user to list permissions for. :type username: str :param resource: The resource (keyspace or table), if None, permissions for all resources are listed. :type resource: str :param resource_type: The resource_type (keyspace or table), defaults to 'keyspace'. :type resource_type: str :param permission: A permission name (e.g. select), if None, all permissions are listed. :type permission: str :param contact_points: The Cassandra cluster addresses, can either be a string or a list of IPs. :type contact_points: str | list[str] :param cql_user: The Cassandra user if authentication is turned on. :type cql_user: str :param cql_pass: The Cassandra user password if authentication is turned on. :type cql_pass: str :param port: The Cassandra cluster port, defaults to None. :type port: int :return: Dictionary of permissions. :rtype: dict CLI Example: .. code-block:: bash salt 'minion1' cassandra_cql.list_permissions salt 'minion1' cassandra_cql.list_permissions username=joe resource=test_keyspace permission=select salt 'minion1' cassandra_cql.list_permissions username=joe resource=test_table resource_type=table \ permission=select contact_points=minion1 ''' keyspace_cql = "{0} {1}".format(resource_type, resource) if resource else "all keyspaces" permission_cql = "{0} permission".format(permission) if permission else "all permissions" query = "list {0} on {1}".format(permission_cql, keyspace_cql) if username: query = "{0} of {1}".format(query, username) log.debug("Attempting to list permissions with query '%s'", query) ret = {} try: ret = cql_query(query, contact_points, port, cql_user, cql_pass) except CommandExecutionError: log.critical('Could not list permissions.') raise except BaseException as e: log.critical('Unexpected error while listing permissions: %s', e) raise return ret def grant_permission(username, resource=None, resource_type='keyspace', permission=None, contact_points=None, port=None, cql_user=None, cql_pass=None): ''' Grant permissions to a user. :param username: The name of the user to grant permissions to. :type username: str :param resource: The resource (keyspace or table), if None, permissions for all resources are granted. :type resource: str :param resource_type: The resource_type (keyspace or table), defaults to 'keyspace'. :type resource_type: str :param permission: A permission name (e.g. select), if None, all permissions are granted. :type permission: str :param contact_points: The Cassandra cluster addresses, can either be a string or a list of IPs. :type contact_points: str | list[str] :param cql_user: The Cassandra user if authentication is turned on. :type cql_user: str :param cql_pass: The Cassandra user password if authentication is turned on. :type cql_pass: str :param port: The Cassandra cluster port, defaults to None. :type port: int :return: :rtype: CLI Example: .. code-block:: bash salt 'minion1' cassandra_cql.grant_permission salt 'minion1' cassandra_cql.grant_permission username=joe resource=test_keyspace permission=select salt 'minion1' cassandra_cql.grant_permission username=joe resource=test_table resource_type=table \ permission=select contact_points=minion1 ''' permission_cql = "grant {0}".format(permission) if permission else "grant all permissions" resource_cql = "on {0} {1}".format(resource_type, resource) if resource else "on all keyspaces" query = "{0} {1} to {2}".format(permission_cql, resource_cql, username) log.debug("Attempting to grant permissions with query '%s'", query) try: cql_query(query, contact_points, port, cql_user, cql_pass) except CommandExecutionError: log.critical('Could not grant permissions.') raise except BaseException as e: log.critical('Unexpected error while granting permissions: %s', e) raise return True
saltstack/salt
salt/modules/cassandra_cql.py
keyspace_exists
python
def keyspace_exists(keyspace, contact_points=None, port=None, cql_user=None, cql_pass=None): ''' Check if a keyspace exists in a Cassandra cluster. :param keyspace The keyspace name to check for. :type keyspace: str :param contact_points: The Cassandra cluster addresses, can either be a string or a list of IPs. :type contact_points: str | list[str] :param cql_user: The Cassandra user if authentication is turned on. :type cql_user: str :param cql_pass: The Cassandra user password if authentication is turned on. :type cql_pass: str :param port: The Cassandra cluster port, defaults to None. :type port: int :return: The info for the keyspace or False if it does not exist. :rtype: dict CLI Example: .. code-block:: bash salt 'minion1' cassandra_cql.keyspace_exists keyspace=system ''' query = { '2': '''select keyspace_name from system.schema_keyspaces where keyspace_name = '{0}';'''.format(keyspace), '3': '''select keyspace_name from system_schema.keyspaces where keyspace_name = '{0}';'''.format(keyspace), } try: ret = cql_query(query, contact_points, port, cql_user, cql_pass) except CommandExecutionError: log.critical('Could not determine if keyspace exists.') raise except BaseException as e: log.critical('Unexpected error while determining if keyspace exists: %s', e) raise return True if ret else False
Check if a keyspace exists in a Cassandra cluster. :param keyspace The keyspace name to check for. :type keyspace: str :param contact_points: The Cassandra cluster addresses, can either be a string or a list of IPs. :type contact_points: str | list[str] :param cql_user: The Cassandra user if authentication is turned on. :type cql_user: str :param cql_pass: The Cassandra user password if authentication is turned on. :type cql_pass: str :param port: The Cassandra cluster port, defaults to None. :type port: int :return: The info for the keyspace or False if it does not exist. :rtype: dict CLI Example: .. code-block:: bash salt 'minion1' cassandra_cql.keyspace_exists keyspace=system
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/cassandra_cql.py#L646-L685
[ "def cql_query(query, contact_points=None, port=None, cql_user=None, cql_pass=None):\n '''\n Run a query on a Cassandra cluster and return a dictionary.\n\n :param query: The query to execute.\n :type query: str\n :param contact_points: The Cassandra cluster addresses, can either be a string or a list of IPs.\n :type contact_points: str | list[str]\n :param cql_user: The Cassandra user if authentication is turned on.\n :type cql_user: str\n :param cql_pass: The Cassandra user password if authentication is turned on.\n :type cql_pass: str\n :param port: The Cassandra cluster port, defaults to None.\n :type port: int\n :param params: The parameters for the query, optional.\n :type params: str\n :return: A dictionary from the return values of the query\n :rtype: list[dict]\n\n CLI Example:\n\n .. code-block:: bash\n\n salt 'cassandra-server' cassandra_cql.cql_query \"SELECT * FROM users_by_name WHERE first_name = 'jane'\"\n '''\n try:\n cluster, session = _connect(contact_points=contact_points, port=port, cql_user=cql_user, cql_pass=cql_pass)\n except CommandExecutionError:\n log.critical('Could not get Cassandra cluster session.')\n raise\n except BaseException as e:\n log.critical('Unexpected error while getting Cassandra cluster session: %s', e)\n raise\n\n session.row_factory = dict_factory\n ret = []\n\n # Cassandra changed their internal schema from v2 to v3\n # If the query contains a dictionary sorted by versions\n # Find the query for the current cluster version.\n # https://issues.apache.org/jira/browse/CASSANDRA-6717\n if isinstance(query, dict):\n cluster_version = version(contact_points=contact_points,\n port=port,\n cql_user=cql_user,\n cql_pass=cql_pass)\n match = re.match(r'^(\\d+)\\.(\\d+)(?:\\.(\\d+))?', cluster_version)\n major, minor, point = match.groups()\n # try to find the specific version in the query dictionary\n # then try the major version\n # otherwise default to the highest version number\n try:\n query = query[cluster_version]\n except KeyError:\n query = query.get(major, max(query))\n log.debug('New query is: %s', query)\n\n try:\n results = session.execute(query)\n except BaseException as e:\n log.error('Failed to execute query: %s\\n reason: %s', query, e)\n msg = \"ERROR: Cassandra query failed: {0} reason: {1}\".format(query, e)\n raise CommandExecutionError(msg)\n\n if results:\n for result in results:\n values = {}\n for key, value in six.iteritems(result):\n # Salt won't return dictionaries with odd types like uuid.UUID\n if not isinstance(value, six.text_type):\n # Must support Cassandra collection types.\n # Namely, Cassandras set, list, and map collections.\n if not isinstance(value, (set, list, dict)):\n value = six.text_type(value)\n values[key] = value\n ret.append(values)\n\n return ret\n" ]
# -*- coding: utf-8 -*- ''' Cassandra Database Module .. versionadded:: 2015.5.0 This module works with Cassandra v2 and v3 and hence generates queries based on the internal schema of said version. :depends: DataStax Python Driver for Apache Cassandra https://github.com/datastax/python-driver pip install cassandra-driver :referenced by: Salt's cassandra_cql returner :configuration: The Cassandra cluster members and connection port can either be specified in the master or minion config, the minion's pillar or be passed to the module. Example configuration in the config for a single node: .. code-block:: yaml cassandra: cluster: 192.168.50.10 port: 9000 Example configuration in the config for a cluster: .. code-block:: yaml cassandra: cluster: - 192.168.50.10 - 192.168.50.11 - 192.168.50.12 port: 9000 username: cas_admin .. versionchanged:: 2016.11.0 Added support for ``ssl_options`` and ``protocol_version``. Example configuration with `ssl options <http://datastax.github.io/python-driver/api/cassandra/cluster.html#cassandra.cluster.Cluster.ssl_options>`_: If ``ssl_options`` are present in cassandra config the cassandra_cql returner will use SSL. SSL isn't used if ``ssl_options`` isn't specified. .. code-block:: yaml cassandra: cluster: - 192.168.50.10 - 192.168.50.11 - 192.168.50.12 port: 9000 username: cas_admin ssl_options: ca_certs: /etc/ssl/certs/ca-bundle.trust.crt # SSL version should be one from the ssl module # This is an optional parameter ssl_version: PROTOCOL_TLSv1 Additionally you can also specify the ``protocol_version`` to `use <http://datastax.github.io/python-driver/api/cassandra/cluster.html#cassandra.cluster.Cluster.ssl_options>`_. .. code-block:: yaml cassandra: cluster: - 192.168.50.10 - 192.168.50.11 - 192.168.50.12 port: 9000 username: cas_admin # defaults to 4, if not set protocol_version: 3 ''' # Import Python Libs from __future__ import absolute_import, unicode_literals, print_function import logging import re import ssl # Import Salt Libs import salt.utils.json from salt.exceptions import CommandExecutionError # Import 3rd-party libs from salt.ext import six from salt.ext.six.moves import range import salt.utils.versions SSL_VERSION = 'ssl_version' log = logging.getLogger(__name__) __virtualname__ = 'cassandra_cql' HAS_DRIVER = False try: # pylint: disable=import-error,no-name-in-module from cassandra.cluster import Cluster from cassandra.cluster import NoHostAvailable from cassandra.connection import ConnectionException, \ ConnectionShutdown, OperationTimedOut from cassandra.auth import PlainTextAuthProvider from cassandra.query import dict_factory # pylint: enable=import-error,no-name-in-module HAS_DRIVER = True except ImportError: pass def __virtual__(): ''' Return virtual name of the module only if the python driver can be loaded. :return: The virtual name of the module. :rtype: str ''' if HAS_DRIVER: return __virtualname__ return (False, 'Cannot load cassandra_cql module: python driver not found') def _async_log_errors(errors): log.error('Cassandra_cql asynchronous call returned: %s', errors) def _load_properties(property_name, config_option, set_default=False, default=None): ''' Load properties for the cassandra module from config or pillar. :param property_name: The property to load. :type property_name: str or list of str :param config_option: The name of the config option. :type config_option: str :param set_default: Should a default be set if not found in config. :type set_default: bool :param default: The default value to be set. :type default: str or int :return: The property fetched from the configuration or default. :rtype: str or list of str ''' if not property_name: log.debug("No property specified in function, trying to load from salt configuration") try: options = __salt__['config.option']('cassandra') except BaseException as e: log.error("Failed to get cassandra config options. Reason: %s", e) raise loaded_property = options.get(config_option) if not loaded_property: if set_default: log.debug('Setting default Cassandra %s to %s', config_option, default) loaded_property = default else: log.error('No cassandra %s specified in the configuration or passed to the module.', config_option) raise CommandExecutionError("ERROR: Cassandra {0} cannot be empty.".format(config_option)) return loaded_property return property_name def _get_ssl_opts(): ''' Parse out ssl_options for Cassandra cluster connection. Make sure that the ssl_version (if any specified) is valid. ''' sslopts = __salt__['config.option']('cassandra').get('ssl_options', None) ssl_opts = {} if sslopts: ssl_opts['ca_certs'] = sslopts['ca_certs'] if SSL_VERSION in sslopts: if not sslopts[SSL_VERSION].startswith('PROTOCOL_'): valid_opts = ', '.join( [x for x in dir(ssl) if x.startswith('PROTOCOL_')] ) raise CommandExecutionError('Invalid protocol_version ' 'specified! ' 'Please make sure ' 'that the ssl protocol' 'version is one from the SSL' 'module. ' 'Valid options are ' '{0}'.format(valid_opts)) else: ssl_opts[SSL_VERSION] = \ getattr(ssl, sslopts[SSL_VERSION]) return ssl_opts else: return None def _connect(contact_points=None, port=None, cql_user=None, cql_pass=None, protocol_version=None): ''' Connect to a Cassandra cluster. :param contact_points: The Cassandra cluster addresses, can either be a string or a list of IPs. :type contact_points: str or list of str :param cql_user: The Cassandra user if authentication is turned on. :type cql_user: str :param cql_pass: The Cassandra user password if authentication is turned on. :type cql_pass: str :param port: The Cassandra cluster port, defaults to None. :type port: int :param protocol_version: Cassandra protocol version to use. :type port: int :return: The session and cluster objects. :rtype: cluster object, session object ''' # Lazy load the Cassandra cluster and session for this module by creating a # cluster and session when cql_query is called the first time. Get the # Cassandra cluster and session from this module's __context__ after it is # loaded the first time cql_query is called. # # TODO: Call cluster.shutdown() when the module is unloaded on # master/minion shutdown. Currently, Master.shutdown() and Minion.shutdown() # do nothing to allow loaded modules to gracefully handle resources stored # in __context__ (i.e. connection pools). This means that the connection # pool is orphaned and Salt relies on Cassandra to reclaim connections. # Perhaps if Master/Minion daemons could be enhanced to call an "__unload__" # function, or something similar for each loaded module, connection pools # and the like can be gracefully reclaimed/shutdown. if (__context__ and 'cassandra_cql_returner_cluster' in __context__ and 'cassandra_cql_returner_session' in __context__): return __context__['cassandra_cql_returner_cluster'], __context__['cassandra_cql_returner_session'] else: contact_points = _load_properties(property_name=contact_points, config_option='cluster') contact_points = contact_points if isinstance(contact_points, list) else contact_points.split(',') port = _load_properties(property_name=port, config_option='port', set_default=True, default=9042) cql_user = _load_properties(property_name=cql_user, config_option='username', set_default=True, default="cassandra") cql_pass = _load_properties(property_name=cql_pass, config_option='password', set_default=True, default="cassandra") protocol_version = _load_properties(property_name=protocol_version, config_option='protocol_version', set_default=True, default=4) try: auth_provider = PlainTextAuthProvider(username=cql_user, password=cql_pass) ssl_opts = _get_ssl_opts() if ssl_opts: cluster = Cluster(contact_points, port=port, auth_provider=auth_provider, ssl_options=ssl_opts, protocol_version=protocol_version, compression=True) else: cluster = Cluster(contact_points, port=port, auth_provider=auth_provider, protocol_version=protocol_version, compression=True) for recontimes in range(1, 4): try: session = cluster.connect() break except OperationTimedOut: log.warning('Cassandra cluster.connect timed out, try %s', recontimes) if recontimes >= 3: raise # TODO: Call cluster.shutdown() when the module is unloaded on shutdown. __context__['cassandra_cql_returner_cluster'] = cluster __context__['cassandra_cql_returner_session'] = session __context__['cassandra_cql_prepared'] = {} log.debug('Successfully connected to Cassandra cluster at %s', contact_points) return cluster, session except TypeError: pass except (ConnectionException, ConnectionShutdown, NoHostAvailable): log.error('Could not connect to Cassandra cluster at %s', contact_points) raise CommandExecutionError('ERROR: Could not connect to Cassandra cluster.') def cql_query(query, contact_points=None, port=None, cql_user=None, cql_pass=None): ''' Run a query on a Cassandra cluster and return a dictionary. :param query: The query to execute. :type query: str :param contact_points: The Cassandra cluster addresses, can either be a string or a list of IPs. :type contact_points: str | list[str] :param cql_user: The Cassandra user if authentication is turned on. :type cql_user: str :param cql_pass: The Cassandra user password if authentication is turned on. :type cql_pass: str :param port: The Cassandra cluster port, defaults to None. :type port: int :param params: The parameters for the query, optional. :type params: str :return: A dictionary from the return values of the query :rtype: list[dict] CLI Example: .. code-block:: bash salt 'cassandra-server' cassandra_cql.cql_query "SELECT * FROM users_by_name WHERE first_name = 'jane'" ''' try: cluster, session = _connect(contact_points=contact_points, port=port, cql_user=cql_user, cql_pass=cql_pass) except CommandExecutionError: log.critical('Could not get Cassandra cluster session.') raise except BaseException as e: log.critical('Unexpected error while getting Cassandra cluster session: %s', e) raise session.row_factory = dict_factory ret = [] # Cassandra changed their internal schema from v2 to v3 # If the query contains a dictionary sorted by versions # Find the query for the current cluster version. # https://issues.apache.org/jira/browse/CASSANDRA-6717 if isinstance(query, dict): cluster_version = version(contact_points=contact_points, port=port, cql_user=cql_user, cql_pass=cql_pass) match = re.match(r'^(\d+)\.(\d+)(?:\.(\d+))?', cluster_version) major, minor, point = match.groups() # try to find the specific version in the query dictionary # then try the major version # otherwise default to the highest version number try: query = query[cluster_version] except KeyError: query = query.get(major, max(query)) log.debug('New query is: %s', query) try: results = session.execute(query) except BaseException as e: log.error('Failed to execute query: %s\n reason: %s', query, e) msg = "ERROR: Cassandra query failed: {0} reason: {1}".format(query, e) raise CommandExecutionError(msg) if results: for result in results: values = {} for key, value in six.iteritems(result): # Salt won't return dictionaries with odd types like uuid.UUID if not isinstance(value, six.text_type): # Must support Cassandra collection types. # Namely, Cassandras set, list, and map collections. if not isinstance(value, (set, list, dict)): value = six.text_type(value) values[key] = value ret.append(values) return ret def cql_query_with_prepare(query, statement_name, statement_arguments, callback_errors=None, contact_points=None, port=None, cql_user=None, cql_pass=None, **kwargs): ''' Run a query on a Cassandra cluster and return a dictionary. This function should not be used asynchronously for SELECTs -- it will not return anything and we don't currently have a mechanism for handling a future that will return results. :param query: The query to execute. :type query: str :param statement_name: Name to assign the prepared statement in the __context__ dictionary :type statement_name: str :param statement_arguments: Bind parameters for the SQL statement :type statement_arguments: list[str] :param async: Run this query in asynchronous mode :type async: bool :param callback_errors: Function to call after query runs if there is an error :type callback_errors: Function callable :param contact_points: The Cassandra cluster addresses, can either be a string or a list of IPs. :type contact_points: str | list[str] :param cql_user: The Cassandra user if authentication is turned on. :type cql_user: str :param cql_pass: The Cassandra user password if authentication is turned on. :type cql_pass: str :param port: The Cassandra cluster port, defaults to None. :type port: int :param params: The parameters for the query, optional. :type params: str :return: A dictionary from the return values of the query :rtype: list[dict] CLI Example: .. code-block:: bash # Insert data asynchronously salt this-node cassandra_cql.cql_query_with_prepare "name_insert" "INSERT INTO USERS (first_name, last_name) VALUES (?, ?)" \ statement_arguments=['John','Doe'], asynchronous=True # Select data, should not be asynchronous because there is not currently a facility to return data from a future salt this-node cassandra_cql.cql_query_with_prepare "name_select" "SELECT * FROM USERS WHERE first_name=?" \ statement_arguments=['John'] ''' # Backward-compatibility with Python 3.7: "async" is a reserved word asynchronous = kwargs.get('async', False) try: cluster, session = _connect(contact_points=contact_points, port=port, cql_user=cql_user, cql_pass=cql_pass) except CommandExecutionError: log.critical('Could not get Cassandra cluster session.') raise except BaseException as e: log.critical('Unexpected error while getting Cassandra cluster session: %s', e) raise if statement_name not in __context__['cassandra_cql_prepared']: try: bound_statement = session.prepare(query) __context__['cassandra_cql_prepared'][statement_name] = bound_statement except BaseException as e: log.critical('Unexpected error while preparing SQL statement: %s', e) raise else: bound_statement = __context__['cassandra_cql_prepared'][statement_name] session.row_factory = dict_factory ret = [] try: if asynchronous: future_results = session.execute_async(bound_statement.bind(statement_arguments)) # future_results.add_callbacks(_async_log_errors) else: results = session.execute(bound_statement.bind(statement_arguments)) except BaseException as e: log.error('Failed to execute query: %s\n reason: %s', query, e) msg = "ERROR: Cassandra query failed: {0} reason: {1}".format(query, e) raise CommandExecutionError(msg) if not asynchronous and results: for result in results: values = {} for key, value in six.iteritems(result): # Salt won't return dictionaries with odd types like uuid.UUID if not isinstance(value, six.text_type): # Must support Cassandra collection types. # Namely, Cassandras set, list, and map collections. if not isinstance(value, (set, list, dict)): value = six.text_type(value) values[key] = value ret.append(values) # If this was a synchronous call, then we either have an empty list # because there was no return, or we have a return # If this was an asynchronous call we only return the empty list return ret def version(contact_points=None, port=None, cql_user=None, cql_pass=None): ''' Show the Cassandra version. :param contact_points: The Cassandra cluster addresses, can either be a string or a list of IPs. :type contact_points: str | list[str] :param cql_user: The Cassandra user if authentication is turned on. :type cql_user: str :param cql_pass: The Cassandra user password if authentication is turned on. :type cql_pass: str :param port: The Cassandra cluster port, defaults to None. :type port: int :return: The version for this Cassandra cluster. :rtype: str CLI Example: .. code-block:: bash salt 'minion1' cassandra_cql.version salt 'minion1' cassandra_cql.version contact_points=minion1 ''' query = '''select release_version from system.local limit 1;''' try: ret = cql_query(query, contact_points, port, cql_user, cql_pass) except CommandExecutionError: log.critical('Could not get Cassandra version.') raise except BaseException as e: log.critical('Unexpected error while getting Cassandra version: %s', e) raise return ret[0].get('release_version') def info(contact_points=None, port=None, cql_user=None, cql_pass=None): ''' Show the Cassandra information for this cluster. :param contact_points: The Cassandra cluster addresses, can either be a string or a list of IPs. :type contact_points: str | list[str] :param cql_user: The Cassandra user if authentication is turned on. :type cql_user: str :param cql_pass: The Cassandra user password if authentication is turned on. :type cql_pass: str :param port: The Cassandra cluster port, defaults to None. :type port: int :return: The information for this Cassandra cluster. :rtype: dict CLI Example: .. code-block:: bash salt 'minion1' cassandra_cql.info salt 'minion1' cassandra_cql.info contact_points=minion1 ''' query = '''select cluster_name, data_center, partitioner, host_id, rack, release_version, cql_version, schema_version, thrift_version from system.local limit 1;''' ret = {} try: ret = cql_query(query, contact_points, port, cql_user, cql_pass) except CommandExecutionError: log.critical('Could not list Cassandra info.') raise except BaseException as e: log.critical('Unexpected error while listing Cassandra info: %s', e) raise return ret def list_keyspaces(contact_points=None, port=None, cql_user=None, cql_pass=None): ''' List keyspaces in a Cassandra cluster. :param contact_points: The Cassandra cluster addresses, can either be a string or a list of IPs. :type contact_points: str | list[str] :param cql_user: The Cassandra user if authentication is turned on. :type cql_user: str :param cql_pass: The Cassandra user password if authentication is turned on. :type cql_pass: str :param port: The Cassandra cluster port, defaults to None. :type port: int :return: The keyspaces in this Cassandra cluster. :rtype: list[dict] CLI Example: .. code-block:: bash salt 'minion1' cassandra_cql.list_keyspaces salt 'minion1' cassandra_cql.list_keyspaces contact_points=minion1 port=9000 ''' query = { '2': 'select keyspace_name from system.schema_keyspaces;', '3': 'select keyspace_name from system_schema.keyspaces;', } ret = {} try: ret = cql_query(query, contact_points, port, cql_user, cql_pass) except CommandExecutionError: log.critical('Could not list keyspaces.') raise except BaseException as e: log.critical('Unexpected error while listing keyspaces: %s', e) raise return ret def list_column_families(keyspace=None, contact_points=None, port=None, cql_user=None, cql_pass=None): ''' List column families in a Cassandra cluster for all keyspaces or just the provided one. :param keyspace: The keyspace to provide the column families for, optional. :type keyspace: str :param contact_points: The Cassandra cluster addresses, can either be a string or a list of IPs. :type contact_points: str | list[str] :param cql_user: The Cassandra user if authentication is turned on. :type cql_user: str :param cql_pass: The Cassandra user password if authentication is turned on. :type cql_pass: str :param port: The Cassandra cluster port, defaults to None. :type port: int :return: The column families in this Cassandra cluster. :rtype: list[dict] CLI Example: .. code-block:: bash salt 'minion1' cassandra_cql.list_column_families salt 'minion1' cassandra_cql.list_column_families contact_points=minion1 salt 'minion1' cassandra_cql.list_column_families keyspace=system ''' where_clause = "where keyspace_name = '{0}'".format(keyspace) if keyspace else "" query = { '2': '''select columnfamily_name from system.schema_columnfamilies {0};'''.format(where_clause), '3': '''select column_name from system_schema.columns {0};'''.format(where_clause), } ret = {} try: ret = cql_query(query, contact_points, port, cql_user, cql_pass) except CommandExecutionError: log.critical('Could not list column families.') raise except BaseException as e: log.critical('Unexpected error while listing column families: %s', e) raise return ret def create_keyspace(keyspace, replication_strategy='SimpleStrategy', replication_factor=1, replication_datacenters=None, contact_points=None, port=None, cql_user=None, cql_pass=None): ''' Create a new keyspace in Cassandra. :param keyspace: The keyspace name :type keyspace: str :param replication_strategy: either `SimpleStrategy` or `NetworkTopologyStrategy` :type replication_strategy: str :param replication_factor: number of replicas of data on multiple nodes. not used if using NetworkTopologyStrategy :type replication_factor: int :param replication_datacenters: string or dict of datacenter names to replication factors, required if using NetworkTopologyStrategy (will be a dict if coming from state file). :type replication_datacenters: str | dict[str, int] :param contact_points: The Cassandra cluster addresses, can either be a string or a list of IPs. :type contact_points: str | list[str] :param cql_user: The Cassandra user if authentication is turned on. :type cql_user: str :param cql_pass: The Cassandra user password if authentication is turned on. :type cql_pass: str :param port: The Cassandra cluster port, defaults to None. :type port: int :return: The info for the keyspace or False if it does not exist. :rtype: dict CLI Example: .. code-block:: bash # CLI Example: salt 'minion1' cassandra_cql.create_keyspace keyspace=newkeyspace salt 'minion1' cassandra_cql.create_keyspace keyspace=newkeyspace replication_strategy=NetworkTopologyStrategy \ replication_datacenters='{"datacenter_1": 3, "datacenter_2": 2}' ''' existing_keyspace = keyspace_exists(keyspace, contact_points, port) if not existing_keyspace: # Add the strategy, replication_factor, etc. replication_map = { 'class': replication_strategy } if replication_datacenters: if isinstance(replication_datacenters, six.string_types): try: replication_datacenter_map = salt.utils.json.loads(replication_datacenters) replication_map.update(**replication_datacenter_map) except BaseException: # pylint: disable=W0703 log.error("Could not load json replication_datacenters.") return False else: replication_map.update(**replication_datacenters) else: replication_map['replication_factor'] = replication_factor query = '''create keyspace {0} with replication = {1} and durable_writes = true;'''.format(keyspace, replication_map) try: cql_query(query, contact_points, port, cql_user, cql_pass) except CommandExecutionError: log.critical('Could not create keyspace.') raise except BaseException as e: log.critical('Unexpected error while creating keyspace: %s', e) raise def drop_keyspace(keyspace, contact_points=None, port=None, cql_user=None, cql_pass=None): ''' Drop a keyspace if it exists in a Cassandra cluster. :param keyspace: The keyspace to drop. :type keyspace: str :param contact_points: The Cassandra cluster addresses, can either be a string or a list of IPs. :type contact_points: str | list[str] :param cql_user: The Cassandra user if authentication is turned on. :type cql_user: str :param cql_pass: The Cassandra user password if authentication is turned on. :type cql_pass: str :param port: The Cassandra cluster port, defaults to None. :type port: int :return: The info for the keyspace or False if it does not exist. :rtype: dict CLI Example: .. code-block:: bash salt 'minion1' cassandra_cql.drop_keyspace keyspace=test salt 'minion1' cassandra_cql.drop_keyspace keyspace=test contact_points=minion1 ''' existing_keyspace = keyspace_exists(keyspace, contact_points, port) if existing_keyspace: query = '''drop keyspace {0};'''.format(keyspace) try: cql_query(query, contact_points, port, cql_user, cql_pass) except CommandExecutionError: log.critical('Could not drop keyspace.') raise except BaseException as e: log.critical('Unexpected error while dropping keyspace: %s', e) raise return True def list_users(contact_points=None, port=None, cql_user=None, cql_pass=None): ''' List existing users in this Cassandra cluster. :param contact_points: The Cassandra cluster addresses, can either be a string or a list of IPs. :type contact_points: str | list[str] :param port: The Cassandra cluster port, defaults to None. :type port: int :param cql_user: The Cassandra user if authentication is turned on. :type cql_user: str :param cql_pass: The Cassandra user password if authentication is turned on. :type cql_pass: str :return: The list of existing users. :rtype: dict CLI Example: .. code-block:: bash salt 'minion1' cassandra_cql.list_users salt 'minion1' cassandra_cql.list_users contact_points=minion1 ''' query = "list users;" ret = {} try: ret = cql_query(query, contact_points, port, cql_user, cql_pass) except CommandExecutionError: log.critical('Could not list users.') raise except BaseException as e: log.critical('Unexpected error while listing users: %s', e) raise return ret def create_user(username, password, superuser=False, contact_points=None, port=None, cql_user=None, cql_pass=None): ''' Create a new cassandra user with credentials and superuser status. :param username: The name of the new user. :type username: str :param password: The password of the new user. :type password: str :param superuser: Is the new user going to be a superuser? default: False :type superuser: bool :param contact_points: The Cassandra cluster addresses, can either be a string or a list of IPs. :type contact_points: str | list[str] :param cql_user: The Cassandra user if authentication is turned on. :type cql_user: str :param cql_pass: The Cassandra user password if authentication is turned on. :type cql_pass: str :param port: The Cassandra cluster port, defaults to None. :type port: int :return: :rtype: CLI Example: .. code-block:: bash salt 'minion1' cassandra_cql.create_user username=joe password=secret salt 'minion1' cassandra_cql.create_user username=joe password=secret superuser=True salt 'minion1' cassandra_cql.create_user username=joe password=secret superuser=True contact_points=minion1 ''' superuser_cql = 'superuser' if superuser else 'nosuperuser' query = '''create user if not exists {0} with password '{1}' {2};'''.format(username, password, superuser_cql) log.debug("Attempting to create a new user with username=%s superuser=%s", username, superuser_cql) # The create user query doesn't actually return anything if the query succeeds. # If the query fails, catch the exception, log a messange and raise it again. try: cql_query(query, contact_points, port, cql_user, cql_pass) except CommandExecutionError: log.critical('Could not create user.') raise except BaseException as e: log.critical('Unexpected error while creating user: %s', e) raise return True def create_role(username, password, superuser=False, login=False, contact_points=None, port=None, cql_user=None, cql_pass=None): ''' Create a new cassandra role with credentials and superuser status. :param username: The name of the new user. :type username: str :param password: The password of the new user. :type password: str :param superuser: Is the new role going to be a superuser? default: False :type superuser: bool :param login: Is the new role going to be allowed to log in? default: False :type superuser: bool :param contact_points: The Cassandra cluster addresses, can either be a string or a list of IPs. :type contact_points: str | list[str] :param cql_user: The Cassandra user if authentication is turned on. :type cql_user: str :param cql_pass: The Cassandra user password if authentication is turned on. :type cql_pass: str :param port: The Cassandra cluster port, defaults to None. :type port: int :return: :rtype: CLI Example: .. code-block:: bash salt 'minion1' cassandra_cql.create_role username=joe password=secret salt 'minion1' cassandra_cql.create_role username=joe password=secret superuser=True salt 'minion1' cassandra_cql.create_role username=joe password=secret superuser=True login=True salt 'minion1' cassandra_cql.create_role username=joe password=secret superuser=True login=True contact_points=minion1 ''' superuser_cql = 'superuser = true' if superuser else 'superuser = false' login_cql = 'login = true' if login else 'login = false' query = '''create role if not exists {0} with password '{1}' and {2} and {3} ;'''.format(username, password, superuser_cql, login_cql) log.debug("Attempting to create a new role with username=%s superuser=%s login=%s", username, superuser, login) # The create role query doesn't actually return anything if the query succeeds. # If the query fails, catch the exception, log a messange and raise it again. try: cql_query(query, contact_points, port, cql_user, cql_pass) except CommandExecutionError: log.critical('Could not create role.') raise except BaseException as e: log.critical('Unexpected error while creating role: %s', e) raise return True def list_permissions(username=None, resource=None, resource_type='keyspace', permission=None, contact_points=None, port=None, cql_user=None, cql_pass=None): ''' List permissions. :param username: The name of the user to list permissions for. :type username: str :param resource: The resource (keyspace or table), if None, permissions for all resources are listed. :type resource: str :param resource_type: The resource_type (keyspace or table), defaults to 'keyspace'. :type resource_type: str :param permission: A permission name (e.g. select), if None, all permissions are listed. :type permission: str :param contact_points: The Cassandra cluster addresses, can either be a string or a list of IPs. :type contact_points: str | list[str] :param cql_user: The Cassandra user if authentication is turned on. :type cql_user: str :param cql_pass: The Cassandra user password if authentication is turned on. :type cql_pass: str :param port: The Cassandra cluster port, defaults to None. :type port: int :return: Dictionary of permissions. :rtype: dict CLI Example: .. code-block:: bash salt 'minion1' cassandra_cql.list_permissions salt 'minion1' cassandra_cql.list_permissions username=joe resource=test_keyspace permission=select salt 'minion1' cassandra_cql.list_permissions username=joe resource=test_table resource_type=table \ permission=select contact_points=minion1 ''' keyspace_cql = "{0} {1}".format(resource_type, resource) if resource else "all keyspaces" permission_cql = "{0} permission".format(permission) if permission else "all permissions" query = "list {0} on {1}".format(permission_cql, keyspace_cql) if username: query = "{0} of {1}".format(query, username) log.debug("Attempting to list permissions with query '%s'", query) ret = {} try: ret = cql_query(query, contact_points, port, cql_user, cql_pass) except CommandExecutionError: log.critical('Could not list permissions.') raise except BaseException as e: log.critical('Unexpected error while listing permissions: %s', e) raise return ret def grant_permission(username, resource=None, resource_type='keyspace', permission=None, contact_points=None, port=None, cql_user=None, cql_pass=None): ''' Grant permissions to a user. :param username: The name of the user to grant permissions to. :type username: str :param resource: The resource (keyspace or table), if None, permissions for all resources are granted. :type resource: str :param resource_type: The resource_type (keyspace or table), defaults to 'keyspace'. :type resource_type: str :param permission: A permission name (e.g. select), if None, all permissions are granted. :type permission: str :param contact_points: The Cassandra cluster addresses, can either be a string or a list of IPs. :type contact_points: str | list[str] :param cql_user: The Cassandra user if authentication is turned on. :type cql_user: str :param cql_pass: The Cassandra user password if authentication is turned on. :type cql_pass: str :param port: The Cassandra cluster port, defaults to None. :type port: int :return: :rtype: CLI Example: .. code-block:: bash salt 'minion1' cassandra_cql.grant_permission salt 'minion1' cassandra_cql.grant_permission username=joe resource=test_keyspace permission=select salt 'minion1' cassandra_cql.grant_permission username=joe resource=test_table resource_type=table \ permission=select contact_points=minion1 ''' permission_cql = "grant {0}".format(permission) if permission else "grant all permissions" resource_cql = "on {0} {1}".format(resource_type, resource) if resource else "on all keyspaces" query = "{0} {1} to {2}".format(permission_cql, resource_cql, username) log.debug("Attempting to grant permissions with query '%s'", query) try: cql_query(query, contact_points, port, cql_user, cql_pass) except CommandExecutionError: log.critical('Could not grant permissions.') raise except BaseException as e: log.critical('Unexpected error while granting permissions: %s', e) raise return True
saltstack/salt
salt/modules/cassandra_cql.py
create_keyspace
python
def create_keyspace(keyspace, replication_strategy='SimpleStrategy', replication_factor=1, replication_datacenters=None, contact_points=None, port=None, cql_user=None, cql_pass=None): ''' Create a new keyspace in Cassandra. :param keyspace: The keyspace name :type keyspace: str :param replication_strategy: either `SimpleStrategy` or `NetworkTopologyStrategy` :type replication_strategy: str :param replication_factor: number of replicas of data on multiple nodes. not used if using NetworkTopologyStrategy :type replication_factor: int :param replication_datacenters: string or dict of datacenter names to replication factors, required if using NetworkTopologyStrategy (will be a dict if coming from state file). :type replication_datacenters: str | dict[str, int] :param contact_points: The Cassandra cluster addresses, can either be a string or a list of IPs. :type contact_points: str | list[str] :param cql_user: The Cassandra user if authentication is turned on. :type cql_user: str :param cql_pass: The Cassandra user password if authentication is turned on. :type cql_pass: str :param port: The Cassandra cluster port, defaults to None. :type port: int :return: The info for the keyspace or False if it does not exist. :rtype: dict CLI Example: .. code-block:: bash # CLI Example: salt 'minion1' cassandra_cql.create_keyspace keyspace=newkeyspace salt 'minion1' cassandra_cql.create_keyspace keyspace=newkeyspace replication_strategy=NetworkTopologyStrategy \ replication_datacenters='{"datacenter_1": 3, "datacenter_2": 2}' ''' existing_keyspace = keyspace_exists(keyspace, contact_points, port) if not existing_keyspace: # Add the strategy, replication_factor, etc. replication_map = { 'class': replication_strategy } if replication_datacenters: if isinstance(replication_datacenters, six.string_types): try: replication_datacenter_map = salt.utils.json.loads(replication_datacenters) replication_map.update(**replication_datacenter_map) except BaseException: # pylint: disable=W0703 log.error("Could not load json replication_datacenters.") return False else: replication_map.update(**replication_datacenters) else: replication_map['replication_factor'] = replication_factor query = '''create keyspace {0} with replication = {1} and durable_writes = true;'''.format(keyspace, replication_map) try: cql_query(query, contact_points, port, cql_user, cql_pass) except CommandExecutionError: log.critical('Could not create keyspace.') raise except BaseException as e: log.critical('Unexpected error while creating keyspace: %s', e) raise
Create a new keyspace in Cassandra. :param keyspace: The keyspace name :type keyspace: str :param replication_strategy: either `SimpleStrategy` or `NetworkTopologyStrategy` :type replication_strategy: str :param replication_factor: number of replicas of data on multiple nodes. not used if using NetworkTopologyStrategy :type replication_factor: int :param replication_datacenters: string or dict of datacenter names to replication factors, required if using NetworkTopologyStrategy (will be a dict if coming from state file). :type replication_datacenters: str | dict[str, int] :param contact_points: The Cassandra cluster addresses, can either be a string or a list of IPs. :type contact_points: str | list[str] :param cql_user: The Cassandra user if authentication is turned on. :type cql_user: str :param cql_pass: The Cassandra user password if authentication is turned on. :type cql_pass: str :param port: The Cassandra cluster port, defaults to None. :type port: int :return: The info for the keyspace or False if it does not exist. :rtype: dict CLI Example: .. code-block:: bash # CLI Example: salt 'minion1' cassandra_cql.create_keyspace keyspace=newkeyspace salt 'minion1' cassandra_cql.create_keyspace keyspace=newkeyspace replication_strategy=NetworkTopologyStrategy \ replication_datacenters='{"datacenter_1": 3, "datacenter_2": 2}'
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/cassandra_cql.py#L688-L754
[ "def loads(s, **kwargs):\n '''\n .. versionadded:: 2018.3.0\n\n Wraps json.loads and prevents a traceback in the event that a bytestring is\n passed to the function. (Python < 3.6 cannot load bytestrings)\n\n You can pass an alternate json module (loaded via import_json() above)\n using the _json_module argument)\n '''\n json_module = kwargs.pop('_json_module', json)\n try:\n return json_module.loads(s, **kwargs)\n except TypeError as exc:\n # json.loads cannot load bytestrings in Python < 3.6\n if six.PY3 and isinstance(s, bytes):\n return json_module.loads(salt.utils.stringutils.to_unicode(s), **kwargs)\n else:\n raise exc\n", "def cql_query(query, contact_points=None, port=None, cql_user=None, cql_pass=None):\n '''\n Run a query on a Cassandra cluster and return a dictionary.\n\n :param query: The query to execute.\n :type query: str\n :param contact_points: The Cassandra cluster addresses, can either be a string or a list of IPs.\n :type contact_points: str | list[str]\n :param cql_user: The Cassandra user if authentication is turned on.\n :type cql_user: str\n :param cql_pass: The Cassandra user password if authentication is turned on.\n :type cql_pass: str\n :param port: The Cassandra cluster port, defaults to None.\n :type port: int\n :param params: The parameters for the query, optional.\n :type params: str\n :return: A dictionary from the return values of the query\n :rtype: list[dict]\n\n CLI Example:\n\n .. code-block:: bash\n\n salt 'cassandra-server' cassandra_cql.cql_query \"SELECT * FROM users_by_name WHERE first_name = 'jane'\"\n '''\n try:\n cluster, session = _connect(contact_points=contact_points, port=port, cql_user=cql_user, cql_pass=cql_pass)\n except CommandExecutionError:\n log.critical('Could not get Cassandra cluster session.')\n raise\n except BaseException as e:\n log.critical('Unexpected error while getting Cassandra cluster session: %s', e)\n raise\n\n session.row_factory = dict_factory\n ret = []\n\n # Cassandra changed their internal schema from v2 to v3\n # If the query contains a dictionary sorted by versions\n # Find the query for the current cluster version.\n # https://issues.apache.org/jira/browse/CASSANDRA-6717\n if isinstance(query, dict):\n cluster_version = version(contact_points=contact_points,\n port=port,\n cql_user=cql_user,\n cql_pass=cql_pass)\n match = re.match(r'^(\\d+)\\.(\\d+)(?:\\.(\\d+))?', cluster_version)\n major, minor, point = match.groups()\n # try to find the specific version in the query dictionary\n # then try the major version\n # otherwise default to the highest version number\n try:\n query = query[cluster_version]\n except KeyError:\n query = query.get(major, max(query))\n log.debug('New query is: %s', query)\n\n try:\n results = session.execute(query)\n except BaseException as e:\n log.error('Failed to execute query: %s\\n reason: %s', query, e)\n msg = \"ERROR: Cassandra query failed: {0} reason: {1}\".format(query, e)\n raise CommandExecutionError(msg)\n\n if results:\n for result in results:\n values = {}\n for key, value in six.iteritems(result):\n # Salt won't return dictionaries with odd types like uuid.UUID\n if not isinstance(value, six.text_type):\n # Must support Cassandra collection types.\n # Namely, Cassandras set, list, and map collections.\n if not isinstance(value, (set, list, dict)):\n value = six.text_type(value)\n values[key] = value\n ret.append(values)\n\n return ret\n", "def keyspace_exists(keyspace, contact_points=None, port=None, cql_user=None, cql_pass=None):\n '''\n Check if a keyspace exists in a Cassandra cluster.\n\n :param keyspace The keyspace name to check for.\n :type keyspace: str\n :param contact_points: The Cassandra cluster addresses, can either be a string or a list of IPs.\n :type contact_points: str | list[str]\n :param cql_user: The Cassandra user if authentication is turned on.\n :type cql_user: str\n :param cql_pass: The Cassandra user password if authentication is turned on.\n :type cql_pass: str\n :param port: The Cassandra cluster port, defaults to None.\n :type port: int\n :return: The info for the keyspace or False if it does not exist.\n :rtype: dict\n\n CLI Example:\n\n .. code-block:: bash\n\n salt 'minion1' cassandra_cql.keyspace_exists keyspace=system\n '''\n query = {\n '2': '''select keyspace_name from system.schema_keyspaces\n where keyspace_name = '{0}';'''.format(keyspace),\n '3': '''select keyspace_name from system_schema.keyspaces\n where keyspace_name = '{0}';'''.format(keyspace),\n }\n\n try:\n ret = cql_query(query, contact_points, port, cql_user, cql_pass)\n except CommandExecutionError:\n log.critical('Could not determine if keyspace exists.')\n raise\n except BaseException as e:\n log.critical('Unexpected error while determining if keyspace exists: %s', e)\n raise\n\n return True if ret else False\n" ]
# -*- coding: utf-8 -*- ''' Cassandra Database Module .. versionadded:: 2015.5.0 This module works with Cassandra v2 and v3 and hence generates queries based on the internal schema of said version. :depends: DataStax Python Driver for Apache Cassandra https://github.com/datastax/python-driver pip install cassandra-driver :referenced by: Salt's cassandra_cql returner :configuration: The Cassandra cluster members and connection port can either be specified in the master or minion config, the minion's pillar or be passed to the module. Example configuration in the config for a single node: .. code-block:: yaml cassandra: cluster: 192.168.50.10 port: 9000 Example configuration in the config for a cluster: .. code-block:: yaml cassandra: cluster: - 192.168.50.10 - 192.168.50.11 - 192.168.50.12 port: 9000 username: cas_admin .. versionchanged:: 2016.11.0 Added support for ``ssl_options`` and ``protocol_version``. Example configuration with `ssl options <http://datastax.github.io/python-driver/api/cassandra/cluster.html#cassandra.cluster.Cluster.ssl_options>`_: If ``ssl_options`` are present in cassandra config the cassandra_cql returner will use SSL. SSL isn't used if ``ssl_options`` isn't specified. .. code-block:: yaml cassandra: cluster: - 192.168.50.10 - 192.168.50.11 - 192.168.50.12 port: 9000 username: cas_admin ssl_options: ca_certs: /etc/ssl/certs/ca-bundle.trust.crt # SSL version should be one from the ssl module # This is an optional parameter ssl_version: PROTOCOL_TLSv1 Additionally you can also specify the ``protocol_version`` to `use <http://datastax.github.io/python-driver/api/cassandra/cluster.html#cassandra.cluster.Cluster.ssl_options>`_. .. code-block:: yaml cassandra: cluster: - 192.168.50.10 - 192.168.50.11 - 192.168.50.12 port: 9000 username: cas_admin # defaults to 4, if not set protocol_version: 3 ''' # Import Python Libs from __future__ import absolute_import, unicode_literals, print_function import logging import re import ssl # Import Salt Libs import salt.utils.json from salt.exceptions import CommandExecutionError # Import 3rd-party libs from salt.ext import six from salt.ext.six.moves import range import salt.utils.versions SSL_VERSION = 'ssl_version' log = logging.getLogger(__name__) __virtualname__ = 'cassandra_cql' HAS_DRIVER = False try: # pylint: disable=import-error,no-name-in-module from cassandra.cluster import Cluster from cassandra.cluster import NoHostAvailable from cassandra.connection import ConnectionException, \ ConnectionShutdown, OperationTimedOut from cassandra.auth import PlainTextAuthProvider from cassandra.query import dict_factory # pylint: enable=import-error,no-name-in-module HAS_DRIVER = True except ImportError: pass def __virtual__(): ''' Return virtual name of the module only if the python driver can be loaded. :return: The virtual name of the module. :rtype: str ''' if HAS_DRIVER: return __virtualname__ return (False, 'Cannot load cassandra_cql module: python driver not found') def _async_log_errors(errors): log.error('Cassandra_cql asynchronous call returned: %s', errors) def _load_properties(property_name, config_option, set_default=False, default=None): ''' Load properties for the cassandra module from config or pillar. :param property_name: The property to load. :type property_name: str or list of str :param config_option: The name of the config option. :type config_option: str :param set_default: Should a default be set if not found in config. :type set_default: bool :param default: The default value to be set. :type default: str or int :return: The property fetched from the configuration or default. :rtype: str or list of str ''' if not property_name: log.debug("No property specified in function, trying to load from salt configuration") try: options = __salt__['config.option']('cassandra') except BaseException as e: log.error("Failed to get cassandra config options. Reason: %s", e) raise loaded_property = options.get(config_option) if not loaded_property: if set_default: log.debug('Setting default Cassandra %s to %s', config_option, default) loaded_property = default else: log.error('No cassandra %s specified in the configuration or passed to the module.', config_option) raise CommandExecutionError("ERROR: Cassandra {0} cannot be empty.".format(config_option)) return loaded_property return property_name def _get_ssl_opts(): ''' Parse out ssl_options for Cassandra cluster connection. Make sure that the ssl_version (if any specified) is valid. ''' sslopts = __salt__['config.option']('cassandra').get('ssl_options', None) ssl_opts = {} if sslopts: ssl_opts['ca_certs'] = sslopts['ca_certs'] if SSL_VERSION in sslopts: if not sslopts[SSL_VERSION].startswith('PROTOCOL_'): valid_opts = ', '.join( [x for x in dir(ssl) if x.startswith('PROTOCOL_')] ) raise CommandExecutionError('Invalid protocol_version ' 'specified! ' 'Please make sure ' 'that the ssl protocol' 'version is one from the SSL' 'module. ' 'Valid options are ' '{0}'.format(valid_opts)) else: ssl_opts[SSL_VERSION] = \ getattr(ssl, sslopts[SSL_VERSION]) return ssl_opts else: return None def _connect(contact_points=None, port=None, cql_user=None, cql_pass=None, protocol_version=None): ''' Connect to a Cassandra cluster. :param contact_points: The Cassandra cluster addresses, can either be a string or a list of IPs. :type contact_points: str or list of str :param cql_user: The Cassandra user if authentication is turned on. :type cql_user: str :param cql_pass: The Cassandra user password if authentication is turned on. :type cql_pass: str :param port: The Cassandra cluster port, defaults to None. :type port: int :param protocol_version: Cassandra protocol version to use. :type port: int :return: The session and cluster objects. :rtype: cluster object, session object ''' # Lazy load the Cassandra cluster and session for this module by creating a # cluster and session when cql_query is called the first time. Get the # Cassandra cluster and session from this module's __context__ after it is # loaded the first time cql_query is called. # # TODO: Call cluster.shutdown() when the module is unloaded on # master/minion shutdown. Currently, Master.shutdown() and Minion.shutdown() # do nothing to allow loaded modules to gracefully handle resources stored # in __context__ (i.e. connection pools). This means that the connection # pool is orphaned and Salt relies on Cassandra to reclaim connections. # Perhaps if Master/Minion daemons could be enhanced to call an "__unload__" # function, or something similar for each loaded module, connection pools # and the like can be gracefully reclaimed/shutdown. if (__context__ and 'cassandra_cql_returner_cluster' in __context__ and 'cassandra_cql_returner_session' in __context__): return __context__['cassandra_cql_returner_cluster'], __context__['cassandra_cql_returner_session'] else: contact_points = _load_properties(property_name=contact_points, config_option='cluster') contact_points = contact_points if isinstance(contact_points, list) else contact_points.split(',') port = _load_properties(property_name=port, config_option='port', set_default=True, default=9042) cql_user = _load_properties(property_name=cql_user, config_option='username', set_default=True, default="cassandra") cql_pass = _load_properties(property_name=cql_pass, config_option='password', set_default=True, default="cassandra") protocol_version = _load_properties(property_name=protocol_version, config_option='protocol_version', set_default=True, default=4) try: auth_provider = PlainTextAuthProvider(username=cql_user, password=cql_pass) ssl_opts = _get_ssl_opts() if ssl_opts: cluster = Cluster(contact_points, port=port, auth_provider=auth_provider, ssl_options=ssl_opts, protocol_version=protocol_version, compression=True) else: cluster = Cluster(contact_points, port=port, auth_provider=auth_provider, protocol_version=protocol_version, compression=True) for recontimes in range(1, 4): try: session = cluster.connect() break except OperationTimedOut: log.warning('Cassandra cluster.connect timed out, try %s', recontimes) if recontimes >= 3: raise # TODO: Call cluster.shutdown() when the module is unloaded on shutdown. __context__['cassandra_cql_returner_cluster'] = cluster __context__['cassandra_cql_returner_session'] = session __context__['cassandra_cql_prepared'] = {} log.debug('Successfully connected to Cassandra cluster at %s', contact_points) return cluster, session except TypeError: pass except (ConnectionException, ConnectionShutdown, NoHostAvailable): log.error('Could not connect to Cassandra cluster at %s', contact_points) raise CommandExecutionError('ERROR: Could not connect to Cassandra cluster.') def cql_query(query, contact_points=None, port=None, cql_user=None, cql_pass=None): ''' Run a query on a Cassandra cluster and return a dictionary. :param query: The query to execute. :type query: str :param contact_points: The Cassandra cluster addresses, can either be a string or a list of IPs. :type contact_points: str | list[str] :param cql_user: The Cassandra user if authentication is turned on. :type cql_user: str :param cql_pass: The Cassandra user password if authentication is turned on. :type cql_pass: str :param port: The Cassandra cluster port, defaults to None. :type port: int :param params: The parameters for the query, optional. :type params: str :return: A dictionary from the return values of the query :rtype: list[dict] CLI Example: .. code-block:: bash salt 'cassandra-server' cassandra_cql.cql_query "SELECT * FROM users_by_name WHERE first_name = 'jane'" ''' try: cluster, session = _connect(contact_points=contact_points, port=port, cql_user=cql_user, cql_pass=cql_pass) except CommandExecutionError: log.critical('Could not get Cassandra cluster session.') raise except BaseException as e: log.critical('Unexpected error while getting Cassandra cluster session: %s', e) raise session.row_factory = dict_factory ret = [] # Cassandra changed their internal schema from v2 to v3 # If the query contains a dictionary sorted by versions # Find the query for the current cluster version. # https://issues.apache.org/jira/browse/CASSANDRA-6717 if isinstance(query, dict): cluster_version = version(contact_points=contact_points, port=port, cql_user=cql_user, cql_pass=cql_pass) match = re.match(r'^(\d+)\.(\d+)(?:\.(\d+))?', cluster_version) major, minor, point = match.groups() # try to find the specific version in the query dictionary # then try the major version # otherwise default to the highest version number try: query = query[cluster_version] except KeyError: query = query.get(major, max(query)) log.debug('New query is: %s', query) try: results = session.execute(query) except BaseException as e: log.error('Failed to execute query: %s\n reason: %s', query, e) msg = "ERROR: Cassandra query failed: {0} reason: {1}".format(query, e) raise CommandExecutionError(msg) if results: for result in results: values = {} for key, value in six.iteritems(result): # Salt won't return dictionaries with odd types like uuid.UUID if not isinstance(value, six.text_type): # Must support Cassandra collection types. # Namely, Cassandras set, list, and map collections. if not isinstance(value, (set, list, dict)): value = six.text_type(value) values[key] = value ret.append(values) return ret def cql_query_with_prepare(query, statement_name, statement_arguments, callback_errors=None, contact_points=None, port=None, cql_user=None, cql_pass=None, **kwargs): ''' Run a query on a Cassandra cluster and return a dictionary. This function should not be used asynchronously for SELECTs -- it will not return anything and we don't currently have a mechanism for handling a future that will return results. :param query: The query to execute. :type query: str :param statement_name: Name to assign the prepared statement in the __context__ dictionary :type statement_name: str :param statement_arguments: Bind parameters for the SQL statement :type statement_arguments: list[str] :param async: Run this query in asynchronous mode :type async: bool :param callback_errors: Function to call after query runs if there is an error :type callback_errors: Function callable :param contact_points: The Cassandra cluster addresses, can either be a string or a list of IPs. :type contact_points: str | list[str] :param cql_user: The Cassandra user if authentication is turned on. :type cql_user: str :param cql_pass: The Cassandra user password if authentication is turned on. :type cql_pass: str :param port: The Cassandra cluster port, defaults to None. :type port: int :param params: The parameters for the query, optional. :type params: str :return: A dictionary from the return values of the query :rtype: list[dict] CLI Example: .. code-block:: bash # Insert data asynchronously salt this-node cassandra_cql.cql_query_with_prepare "name_insert" "INSERT INTO USERS (first_name, last_name) VALUES (?, ?)" \ statement_arguments=['John','Doe'], asynchronous=True # Select data, should not be asynchronous because there is not currently a facility to return data from a future salt this-node cassandra_cql.cql_query_with_prepare "name_select" "SELECT * FROM USERS WHERE first_name=?" \ statement_arguments=['John'] ''' # Backward-compatibility with Python 3.7: "async" is a reserved word asynchronous = kwargs.get('async', False) try: cluster, session = _connect(contact_points=contact_points, port=port, cql_user=cql_user, cql_pass=cql_pass) except CommandExecutionError: log.critical('Could not get Cassandra cluster session.') raise except BaseException as e: log.critical('Unexpected error while getting Cassandra cluster session: %s', e) raise if statement_name not in __context__['cassandra_cql_prepared']: try: bound_statement = session.prepare(query) __context__['cassandra_cql_prepared'][statement_name] = bound_statement except BaseException as e: log.critical('Unexpected error while preparing SQL statement: %s', e) raise else: bound_statement = __context__['cassandra_cql_prepared'][statement_name] session.row_factory = dict_factory ret = [] try: if asynchronous: future_results = session.execute_async(bound_statement.bind(statement_arguments)) # future_results.add_callbacks(_async_log_errors) else: results = session.execute(bound_statement.bind(statement_arguments)) except BaseException as e: log.error('Failed to execute query: %s\n reason: %s', query, e) msg = "ERROR: Cassandra query failed: {0} reason: {1}".format(query, e) raise CommandExecutionError(msg) if not asynchronous and results: for result in results: values = {} for key, value in six.iteritems(result): # Salt won't return dictionaries with odd types like uuid.UUID if not isinstance(value, six.text_type): # Must support Cassandra collection types. # Namely, Cassandras set, list, and map collections. if not isinstance(value, (set, list, dict)): value = six.text_type(value) values[key] = value ret.append(values) # If this was a synchronous call, then we either have an empty list # because there was no return, or we have a return # If this was an asynchronous call we only return the empty list return ret def version(contact_points=None, port=None, cql_user=None, cql_pass=None): ''' Show the Cassandra version. :param contact_points: The Cassandra cluster addresses, can either be a string or a list of IPs. :type contact_points: str | list[str] :param cql_user: The Cassandra user if authentication is turned on. :type cql_user: str :param cql_pass: The Cassandra user password if authentication is turned on. :type cql_pass: str :param port: The Cassandra cluster port, defaults to None. :type port: int :return: The version for this Cassandra cluster. :rtype: str CLI Example: .. code-block:: bash salt 'minion1' cassandra_cql.version salt 'minion1' cassandra_cql.version contact_points=minion1 ''' query = '''select release_version from system.local limit 1;''' try: ret = cql_query(query, contact_points, port, cql_user, cql_pass) except CommandExecutionError: log.critical('Could not get Cassandra version.') raise except BaseException as e: log.critical('Unexpected error while getting Cassandra version: %s', e) raise return ret[0].get('release_version') def info(contact_points=None, port=None, cql_user=None, cql_pass=None): ''' Show the Cassandra information for this cluster. :param contact_points: The Cassandra cluster addresses, can either be a string or a list of IPs. :type contact_points: str | list[str] :param cql_user: The Cassandra user if authentication is turned on. :type cql_user: str :param cql_pass: The Cassandra user password if authentication is turned on. :type cql_pass: str :param port: The Cassandra cluster port, defaults to None. :type port: int :return: The information for this Cassandra cluster. :rtype: dict CLI Example: .. code-block:: bash salt 'minion1' cassandra_cql.info salt 'minion1' cassandra_cql.info contact_points=minion1 ''' query = '''select cluster_name, data_center, partitioner, host_id, rack, release_version, cql_version, schema_version, thrift_version from system.local limit 1;''' ret = {} try: ret = cql_query(query, contact_points, port, cql_user, cql_pass) except CommandExecutionError: log.critical('Could not list Cassandra info.') raise except BaseException as e: log.critical('Unexpected error while listing Cassandra info: %s', e) raise return ret def list_keyspaces(contact_points=None, port=None, cql_user=None, cql_pass=None): ''' List keyspaces in a Cassandra cluster. :param contact_points: The Cassandra cluster addresses, can either be a string or a list of IPs. :type contact_points: str | list[str] :param cql_user: The Cassandra user if authentication is turned on. :type cql_user: str :param cql_pass: The Cassandra user password if authentication is turned on. :type cql_pass: str :param port: The Cassandra cluster port, defaults to None. :type port: int :return: The keyspaces in this Cassandra cluster. :rtype: list[dict] CLI Example: .. code-block:: bash salt 'minion1' cassandra_cql.list_keyspaces salt 'minion1' cassandra_cql.list_keyspaces contact_points=minion1 port=9000 ''' query = { '2': 'select keyspace_name from system.schema_keyspaces;', '3': 'select keyspace_name from system_schema.keyspaces;', } ret = {} try: ret = cql_query(query, contact_points, port, cql_user, cql_pass) except CommandExecutionError: log.critical('Could not list keyspaces.') raise except BaseException as e: log.critical('Unexpected error while listing keyspaces: %s', e) raise return ret def list_column_families(keyspace=None, contact_points=None, port=None, cql_user=None, cql_pass=None): ''' List column families in a Cassandra cluster for all keyspaces or just the provided one. :param keyspace: The keyspace to provide the column families for, optional. :type keyspace: str :param contact_points: The Cassandra cluster addresses, can either be a string or a list of IPs. :type contact_points: str | list[str] :param cql_user: The Cassandra user if authentication is turned on. :type cql_user: str :param cql_pass: The Cassandra user password if authentication is turned on. :type cql_pass: str :param port: The Cassandra cluster port, defaults to None. :type port: int :return: The column families in this Cassandra cluster. :rtype: list[dict] CLI Example: .. code-block:: bash salt 'minion1' cassandra_cql.list_column_families salt 'minion1' cassandra_cql.list_column_families contact_points=minion1 salt 'minion1' cassandra_cql.list_column_families keyspace=system ''' where_clause = "where keyspace_name = '{0}'".format(keyspace) if keyspace else "" query = { '2': '''select columnfamily_name from system.schema_columnfamilies {0};'''.format(where_clause), '3': '''select column_name from system_schema.columns {0};'''.format(where_clause), } ret = {} try: ret = cql_query(query, contact_points, port, cql_user, cql_pass) except CommandExecutionError: log.critical('Could not list column families.') raise except BaseException as e: log.critical('Unexpected error while listing column families: %s', e) raise return ret def keyspace_exists(keyspace, contact_points=None, port=None, cql_user=None, cql_pass=None): ''' Check if a keyspace exists in a Cassandra cluster. :param keyspace The keyspace name to check for. :type keyspace: str :param contact_points: The Cassandra cluster addresses, can either be a string or a list of IPs. :type contact_points: str | list[str] :param cql_user: The Cassandra user if authentication is turned on. :type cql_user: str :param cql_pass: The Cassandra user password if authentication is turned on. :type cql_pass: str :param port: The Cassandra cluster port, defaults to None. :type port: int :return: The info for the keyspace or False if it does not exist. :rtype: dict CLI Example: .. code-block:: bash salt 'minion1' cassandra_cql.keyspace_exists keyspace=system ''' query = { '2': '''select keyspace_name from system.schema_keyspaces where keyspace_name = '{0}';'''.format(keyspace), '3': '''select keyspace_name from system_schema.keyspaces where keyspace_name = '{0}';'''.format(keyspace), } try: ret = cql_query(query, contact_points, port, cql_user, cql_pass) except CommandExecutionError: log.critical('Could not determine if keyspace exists.') raise except BaseException as e: log.critical('Unexpected error while determining if keyspace exists: %s', e) raise return True if ret else False def drop_keyspace(keyspace, contact_points=None, port=None, cql_user=None, cql_pass=None): ''' Drop a keyspace if it exists in a Cassandra cluster. :param keyspace: The keyspace to drop. :type keyspace: str :param contact_points: The Cassandra cluster addresses, can either be a string or a list of IPs. :type contact_points: str | list[str] :param cql_user: The Cassandra user if authentication is turned on. :type cql_user: str :param cql_pass: The Cassandra user password if authentication is turned on. :type cql_pass: str :param port: The Cassandra cluster port, defaults to None. :type port: int :return: The info for the keyspace or False if it does not exist. :rtype: dict CLI Example: .. code-block:: bash salt 'minion1' cassandra_cql.drop_keyspace keyspace=test salt 'minion1' cassandra_cql.drop_keyspace keyspace=test contact_points=minion1 ''' existing_keyspace = keyspace_exists(keyspace, contact_points, port) if existing_keyspace: query = '''drop keyspace {0};'''.format(keyspace) try: cql_query(query, contact_points, port, cql_user, cql_pass) except CommandExecutionError: log.critical('Could not drop keyspace.') raise except BaseException as e: log.critical('Unexpected error while dropping keyspace: %s', e) raise return True def list_users(contact_points=None, port=None, cql_user=None, cql_pass=None): ''' List existing users in this Cassandra cluster. :param contact_points: The Cassandra cluster addresses, can either be a string or a list of IPs. :type contact_points: str | list[str] :param port: The Cassandra cluster port, defaults to None. :type port: int :param cql_user: The Cassandra user if authentication is turned on. :type cql_user: str :param cql_pass: The Cassandra user password if authentication is turned on. :type cql_pass: str :return: The list of existing users. :rtype: dict CLI Example: .. code-block:: bash salt 'minion1' cassandra_cql.list_users salt 'minion1' cassandra_cql.list_users contact_points=minion1 ''' query = "list users;" ret = {} try: ret = cql_query(query, contact_points, port, cql_user, cql_pass) except CommandExecutionError: log.critical('Could not list users.') raise except BaseException as e: log.critical('Unexpected error while listing users: %s', e) raise return ret def create_user(username, password, superuser=False, contact_points=None, port=None, cql_user=None, cql_pass=None): ''' Create a new cassandra user with credentials and superuser status. :param username: The name of the new user. :type username: str :param password: The password of the new user. :type password: str :param superuser: Is the new user going to be a superuser? default: False :type superuser: bool :param contact_points: The Cassandra cluster addresses, can either be a string or a list of IPs. :type contact_points: str | list[str] :param cql_user: The Cassandra user if authentication is turned on. :type cql_user: str :param cql_pass: The Cassandra user password if authentication is turned on. :type cql_pass: str :param port: The Cassandra cluster port, defaults to None. :type port: int :return: :rtype: CLI Example: .. code-block:: bash salt 'minion1' cassandra_cql.create_user username=joe password=secret salt 'minion1' cassandra_cql.create_user username=joe password=secret superuser=True salt 'minion1' cassandra_cql.create_user username=joe password=secret superuser=True contact_points=minion1 ''' superuser_cql = 'superuser' if superuser else 'nosuperuser' query = '''create user if not exists {0} with password '{1}' {2};'''.format(username, password, superuser_cql) log.debug("Attempting to create a new user with username=%s superuser=%s", username, superuser_cql) # The create user query doesn't actually return anything if the query succeeds. # If the query fails, catch the exception, log a messange and raise it again. try: cql_query(query, contact_points, port, cql_user, cql_pass) except CommandExecutionError: log.critical('Could not create user.') raise except BaseException as e: log.critical('Unexpected error while creating user: %s', e) raise return True def create_role(username, password, superuser=False, login=False, contact_points=None, port=None, cql_user=None, cql_pass=None): ''' Create a new cassandra role with credentials and superuser status. :param username: The name of the new user. :type username: str :param password: The password of the new user. :type password: str :param superuser: Is the new role going to be a superuser? default: False :type superuser: bool :param login: Is the new role going to be allowed to log in? default: False :type superuser: bool :param contact_points: The Cassandra cluster addresses, can either be a string or a list of IPs. :type contact_points: str | list[str] :param cql_user: The Cassandra user if authentication is turned on. :type cql_user: str :param cql_pass: The Cassandra user password if authentication is turned on. :type cql_pass: str :param port: The Cassandra cluster port, defaults to None. :type port: int :return: :rtype: CLI Example: .. code-block:: bash salt 'minion1' cassandra_cql.create_role username=joe password=secret salt 'minion1' cassandra_cql.create_role username=joe password=secret superuser=True salt 'minion1' cassandra_cql.create_role username=joe password=secret superuser=True login=True salt 'minion1' cassandra_cql.create_role username=joe password=secret superuser=True login=True contact_points=minion1 ''' superuser_cql = 'superuser = true' if superuser else 'superuser = false' login_cql = 'login = true' if login else 'login = false' query = '''create role if not exists {0} with password '{1}' and {2} and {3} ;'''.format(username, password, superuser_cql, login_cql) log.debug("Attempting to create a new role with username=%s superuser=%s login=%s", username, superuser, login) # The create role query doesn't actually return anything if the query succeeds. # If the query fails, catch the exception, log a messange and raise it again. try: cql_query(query, contact_points, port, cql_user, cql_pass) except CommandExecutionError: log.critical('Could not create role.') raise except BaseException as e: log.critical('Unexpected error while creating role: %s', e) raise return True def list_permissions(username=None, resource=None, resource_type='keyspace', permission=None, contact_points=None, port=None, cql_user=None, cql_pass=None): ''' List permissions. :param username: The name of the user to list permissions for. :type username: str :param resource: The resource (keyspace or table), if None, permissions for all resources are listed. :type resource: str :param resource_type: The resource_type (keyspace or table), defaults to 'keyspace'. :type resource_type: str :param permission: A permission name (e.g. select), if None, all permissions are listed. :type permission: str :param contact_points: The Cassandra cluster addresses, can either be a string or a list of IPs. :type contact_points: str | list[str] :param cql_user: The Cassandra user if authentication is turned on. :type cql_user: str :param cql_pass: The Cassandra user password if authentication is turned on. :type cql_pass: str :param port: The Cassandra cluster port, defaults to None. :type port: int :return: Dictionary of permissions. :rtype: dict CLI Example: .. code-block:: bash salt 'minion1' cassandra_cql.list_permissions salt 'minion1' cassandra_cql.list_permissions username=joe resource=test_keyspace permission=select salt 'minion1' cassandra_cql.list_permissions username=joe resource=test_table resource_type=table \ permission=select contact_points=minion1 ''' keyspace_cql = "{0} {1}".format(resource_type, resource) if resource else "all keyspaces" permission_cql = "{0} permission".format(permission) if permission else "all permissions" query = "list {0} on {1}".format(permission_cql, keyspace_cql) if username: query = "{0} of {1}".format(query, username) log.debug("Attempting to list permissions with query '%s'", query) ret = {} try: ret = cql_query(query, contact_points, port, cql_user, cql_pass) except CommandExecutionError: log.critical('Could not list permissions.') raise except BaseException as e: log.critical('Unexpected error while listing permissions: %s', e) raise return ret def grant_permission(username, resource=None, resource_type='keyspace', permission=None, contact_points=None, port=None, cql_user=None, cql_pass=None): ''' Grant permissions to a user. :param username: The name of the user to grant permissions to. :type username: str :param resource: The resource (keyspace or table), if None, permissions for all resources are granted. :type resource: str :param resource_type: The resource_type (keyspace or table), defaults to 'keyspace'. :type resource_type: str :param permission: A permission name (e.g. select), if None, all permissions are granted. :type permission: str :param contact_points: The Cassandra cluster addresses, can either be a string or a list of IPs. :type contact_points: str | list[str] :param cql_user: The Cassandra user if authentication is turned on. :type cql_user: str :param cql_pass: The Cassandra user password if authentication is turned on. :type cql_pass: str :param port: The Cassandra cluster port, defaults to None. :type port: int :return: :rtype: CLI Example: .. code-block:: bash salt 'minion1' cassandra_cql.grant_permission salt 'minion1' cassandra_cql.grant_permission username=joe resource=test_keyspace permission=select salt 'minion1' cassandra_cql.grant_permission username=joe resource=test_table resource_type=table \ permission=select contact_points=minion1 ''' permission_cql = "grant {0}".format(permission) if permission else "grant all permissions" resource_cql = "on {0} {1}".format(resource_type, resource) if resource else "on all keyspaces" query = "{0} {1} to {2}".format(permission_cql, resource_cql, username) log.debug("Attempting to grant permissions with query '%s'", query) try: cql_query(query, contact_points, port, cql_user, cql_pass) except CommandExecutionError: log.critical('Could not grant permissions.') raise except BaseException as e: log.critical('Unexpected error while granting permissions: %s', e) raise return True
saltstack/salt
salt/modules/cassandra_cql.py
drop_keyspace
python
def drop_keyspace(keyspace, contact_points=None, port=None, cql_user=None, cql_pass=None): ''' Drop a keyspace if it exists in a Cassandra cluster. :param keyspace: The keyspace to drop. :type keyspace: str :param contact_points: The Cassandra cluster addresses, can either be a string or a list of IPs. :type contact_points: str | list[str] :param cql_user: The Cassandra user if authentication is turned on. :type cql_user: str :param cql_pass: The Cassandra user password if authentication is turned on. :type cql_pass: str :param port: The Cassandra cluster port, defaults to None. :type port: int :return: The info for the keyspace or False if it does not exist. :rtype: dict CLI Example: .. code-block:: bash salt 'minion1' cassandra_cql.drop_keyspace keyspace=test salt 'minion1' cassandra_cql.drop_keyspace keyspace=test contact_points=minion1 ''' existing_keyspace = keyspace_exists(keyspace, contact_points, port) if existing_keyspace: query = '''drop keyspace {0};'''.format(keyspace) try: cql_query(query, contact_points, port, cql_user, cql_pass) except CommandExecutionError: log.critical('Could not drop keyspace.') raise except BaseException as e: log.critical('Unexpected error while dropping keyspace: %s', e) raise return True
Drop a keyspace if it exists in a Cassandra cluster. :param keyspace: The keyspace to drop. :type keyspace: str :param contact_points: The Cassandra cluster addresses, can either be a string or a list of IPs. :type contact_points: str | list[str] :param cql_user: The Cassandra user if authentication is turned on. :type cql_user: str :param cql_pass: The Cassandra user password if authentication is turned on. :type cql_pass: str :param port: The Cassandra cluster port, defaults to None. :type port: int :return: The info for the keyspace or False if it does not exist. :rtype: dict CLI Example: .. code-block:: bash salt 'minion1' cassandra_cql.drop_keyspace keyspace=test salt 'minion1' cassandra_cql.drop_keyspace keyspace=test contact_points=minion1
train
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/cassandra_cql.py#L757-L794
[ "def cql_query(query, contact_points=None, port=None, cql_user=None, cql_pass=None):\n '''\n Run a query on a Cassandra cluster and return a dictionary.\n\n :param query: The query to execute.\n :type query: str\n :param contact_points: The Cassandra cluster addresses, can either be a string or a list of IPs.\n :type contact_points: str | list[str]\n :param cql_user: The Cassandra user if authentication is turned on.\n :type cql_user: str\n :param cql_pass: The Cassandra user password if authentication is turned on.\n :type cql_pass: str\n :param port: The Cassandra cluster port, defaults to None.\n :type port: int\n :param params: The parameters for the query, optional.\n :type params: str\n :return: A dictionary from the return values of the query\n :rtype: list[dict]\n\n CLI Example:\n\n .. code-block:: bash\n\n salt 'cassandra-server' cassandra_cql.cql_query \"SELECT * FROM users_by_name WHERE first_name = 'jane'\"\n '''\n try:\n cluster, session = _connect(contact_points=contact_points, port=port, cql_user=cql_user, cql_pass=cql_pass)\n except CommandExecutionError:\n log.critical('Could not get Cassandra cluster session.')\n raise\n except BaseException as e:\n log.critical('Unexpected error while getting Cassandra cluster session: %s', e)\n raise\n\n session.row_factory = dict_factory\n ret = []\n\n # Cassandra changed their internal schema from v2 to v3\n # If the query contains a dictionary sorted by versions\n # Find the query for the current cluster version.\n # https://issues.apache.org/jira/browse/CASSANDRA-6717\n if isinstance(query, dict):\n cluster_version = version(contact_points=contact_points,\n port=port,\n cql_user=cql_user,\n cql_pass=cql_pass)\n match = re.match(r'^(\\d+)\\.(\\d+)(?:\\.(\\d+))?', cluster_version)\n major, minor, point = match.groups()\n # try to find the specific version in the query dictionary\n # then try the major version\n # otherwise default to the highest version number\n try:\n query = query[cluster_version]\n except KeyError:\n query = query.get(major, max(query))\n log.debug('New query is: %s', query)\n\n try:\n results = session.execute(query)\n except BaseException as e:\n log.error('Failed to execute query: %s\\n reason: %s', query, e)\n msg = \"ERROR: Cassandra query failed: {0} reason: {1}\".format(query, e)\n raise CommandExecutionError(msg)\n\n if results:\n for result in results:\n values = {}\n for key, value in six.iteritems(result):\n # Salt won't return dictionaries with odd types like uuid.UUID\n if not isinstance(value, six.text_type):\n # Must support Cassandra collection types.\n # Namely, Cassandras set, list, and map collections.\n if not isinstance(value, (set, list, dict)):\n value = six.text_type(value)\n values[key] = value\n ret.append(values)\n\n return ret\n", "def keyspace_exists(keyspace, contact_points=None, port=None, cql_user=None, cql_pass=None):\n '''\n Check if a keyspace exists in a Cassandra cluster.\n\n :param keyspace The keyspace name to check for.\n :type keyspace: str\n :param contact_points: The Cassandra cluster addresses, can either be a string or a list of IPs.\n :type contact_points: str | list[str]\n :param cql_user: The Cassandra user if authentication is turned on.\n :type cql_user: str\n :param cql_pass: The Cassandra user password if authentication is turned on.\n :type cql_pass: str\n :param port: The Cassandra cluster port, defaults to None.\n :type port: int\n :return: The info for the keyspace or False if it does not exist.\n :rtype: dict\n\n CLI Example:\n\n .. code-block:: bash\n\n salt 'minion1' cassandra_cql.keyspace_exists keyspace=system\n '''\n query = {\n '2': '''select keyspace_name from system.schema_keyspaces\n where keyspace_name = '{0}';'''.format(keyspace),\n '3': '''select keyspace_name from system_schema.keyspaces\n where keyspace_name = '{0}';'''.format(keyspace),\n }\n\n try:\n ret = cql_query(query, contact_points, port, cql_user, cql_pass)\n except CommandExecutionError:\n log.critical('Could not determine if keyspace exists.')\n raise\n except BaseException as e:\n log.critical('Unexpected error while determining if keyspace exists: %s', e)\n raise\n\n return True if ret else False\n" ]
# -*- coding: utf-8 -*- ''' Cassandra Database Module .. versionadded:: 2015.5.0 This module works with Cassandra v2 and v3 and hence generates queries based on the internal schema of said version. :depends: DataStax Python Driver for Apache Cassandra https://github.com/datastax/python-driver pip install cassandra-driver :referenced by: Salt's cassandra_cql returner :configuration: The Cassandra cluster members and connection port can either be specified in the master or minion config, the minion's pillar or be passed to the module. Example configuration in the config for a single node: .. code-block:: yaml cassandra: cluster: 192.168.50.10 port: 9000 Example configuration in the config for a cluster: .. code-block:: yaml cassandra: cluster: - 192.168.50.10 - 192.168.50.11 - 192.168.50.12 port: 9000 username: cas_admin .. versionchanged:: 2016.11.0 Added support for ``ssl_options`` and ``protocol_version``. Example configuration with `ssl options <http://datastax.github.io/python-driver/api/cassandra/cluster.html#cassandra.cluster.Cluster.ssl_options>`_: If ``ssl_options`` are present in cassandra config the cassandra_cql returner will use SSL. SSL isn't used if ``ssl_options`` isn't specified. .. code-block:: yaml cassandra: cluster: - 192.168.50.10 - 192.168.50.11 - 192.168.50.12 port: 9000 username: cas_admin ssl_options: ca_certs: /etc/ssl/certs/ca-bundle.trust.crt # SSL version should be one from the ssl module # This is an optional parameter ssl_version: PROTOCOL_TLSv1 Additionally you can also specify the ``protocol_version`` to `use <http://datastax.github.io/python-driver/api/cassandra/cluster.html#cassandra.cluster.Cluster.ssl_options>`_. .. code-block:: yaml cassandra: cluster: - 192.168.50.10 - 192.168.50.11 - 192.168.50.12 port: 9000 username: cas_admin # defaults to 4, if not set protocol_version: 3 ''' # Import Python Libs from __future__ import absolute_import, unicode_literals, print_function import logging import re import ssl # Import Salt Libs import salt.utils.json from salt.exceptions import CommandExecutionError # Import 3rd-party libs from salt.ext import six from salt.ext.six.moves import range import salt.utils.versions SSL_VERSION = 'ssl_version' log = logging.getLogger(__name__) __virtualname__ = 'cassandra_cql' HAS_DRIVER = False try: # pylint: disable=import-error,no-name-in-module from cassandra.cluster import Cluster from cassandra.cluster import NoHostAvailable from cassandra.connection import ConnectionException, \ ConnectionShutdown, OperationTimedOut from cassandra.auth import PlainTextAuthProvider from cassandra.query import dict_factory # pylint: enable=import-error,no-name-in-module HAS_DRIVER = True except ImportError: pass def __virtual__(): ''' Return virtual name of the module only if the python driver can be loaded. :return: The virtual name of the module. :rtype: str ''' if HAS_DRIVER: return __virtualname__ return (False, 'Cannot load cassandra_cql module: python driver not found') def _async_log_errors(errors): log.error('Cassandra_cql asynchronous call returned: %s', errors) def _load_properties(property_name, config_option, set_default=False, default=None): ''' Load properties for the cassandra module from config or pillar. :param property_name: The property to load. :type property_name: str or list of str :param config_option: The name of the config option. :type config_option: str :param set_default: Should a default be set if not found in config. :type set_default: bool :param default: The default value to be set. :type default: str or int :return: The property fetched from the configuration or default. :rtype: str or list of str ''' if not property_name: log.debug("No property specified in function, trying to load from salt configuration") try: options = __salt__['config.option']('cassandra') except BaseException as e: log.error("Failed to get cassandra config options. Reason: %s", e) raise loaded_property = options.get(config_option) if not loaded_property: if set_default: log.debug('Setting default Cassandra %s to %s', config_option, default) loaded_property = default else: log.error('No cassandra %s specified in the configuration or passed to the module.', config_option) raise CommandExecutionError("ERROR: Cassandra {0} cannot be empty.".format(config_option)) return loaded_property return property_name def _get_ssl_opts(): ''' Parse out ssl_options for Cassandra cluster connection. Make sure that the ssl_version (if any specified) is valid. ''' sslopts = __salt__['config.option']('cassandra').get('ssl_options', None) ssl_opts = {} if sslopts: ssl_opts['ca_certs'] = sslopts['ca_certs'] if SSL_VERSION in sslopts: if not sslopts[SSL_VERSION].startswith('PROTOCOL_'): valid_opts = ', '.join( [x for x in dir(ssl) if x.startswith('PROTOCOL_')] ) raise CommandExecutionError('Invalid protocol_version ' 'specified! ' 'Please make sure ' 'that the ssl protocol' 'version is one from the SSL' 'module. ' 'Valid options are ' '{0}'.format(valid_opts)) else: ssl_opts[SSL_VERSION] = \ getattr(ssl, sslopts[SSL_VERSION]) return ssl_opts else: return None def _connect(contact_points=None, port=None, cql_user=None, cql_pass=None, protocol_version=None): ''' Connect to a Cassandra cluster. :param contact_points: The Cassandra cluster addresses, can either be a string or a list of IPs. :type contact_points: str or list of str :param cql_user: The Cassandra user if authentication is turned on. :type cql_user: str :param cql_pass: The Cassandra user password if authentication is turned on. :type cql_pass: str :param port: The Cassandra cluster port, defaults to None. :type port: int :param protocol_version: Cassandra protocol version to use. :type port: int :return: The session and cluster objects. :rtype: cluster object, session object ''' # Lazy load the Cassandra cluster and session for this module by creating a # cluster and session when cql_query is called the first time. Get the # Cassandra cluster and session from this module's __context__ after it is # loaded the first time cql_query is called. # # TODO: Call cluster.shutdown() when the module is unloaded on # master/minion shutdown. Currently, Master.shutdown() and Minion.shutdown() # do nothing to allow loaded modules to gracefully handle resources stored # in __context__ (i.e. connection pools). This means that the connection # pool is orphaned and Salt relies on Cassandra to reclaim connections. # Perhaps if Master/Minion daemons could be enhanced to call an "__unload__" # function, or something similar for each loaded module, connection pools # and the like can be gracefully reclaimed/shutdown. if (__context__ and 'cassandra_cql_returner_cluster' in __context__ and 'cassandra_cql_returner_session' in __context__): return __context__['cassandra_cql_returner_cluster'], __context__['cassandra_cql_returner_session'] else: contact_points = _load_properties(property_name=contact_points, config_option='cluster') contact_points = contact_points if isinstance(contact_points, list) else contact_points.split(',') port = _load_properties(property_name=port, config_option='port', set_default=True, default=9042) cql_user = _load_properties(property_name=cql_user, config_option='username', set_default=True, default="cassandra") cql_pass = _load_properties(property_name=cql_pass, config_option='password', set_default=True, default="cassandra") protocol_version = _load_properties(property_name=protocol_version, config_option='protocol_version', set_default=True, default=4) try: auth_provider = PlainTextAuthProvider(username=cql_user, password=cql_pass) ssl_opts = _get_ssl_opts() if ssl_opts: cluster = Cluster(contact_points, port=port, auth_provider=auth_provider, ssl_options=ssl_opts, protocol_version=protocol_version, compression=True) else: cluster = Cluster(contact_points, port=port, auth_provider=auth_provider, protocol_version=protocol_version, compression=True) for recontimes in range(1, 4): try: session = cluster.connect() break except OperationTimedOut: log.warning('Cassandra cluster.connect timed out, try %s', recontimes) if recontimes >= 3: raise # TODO: Call cluster.shutdown() when the module is unloaded on shutdown. __context__['cassandra_cql_returner_cluster'] = cluster __context__['cassandra_cql_returner_session'] = session __context__['cassandra_cql_prepared'] = {} log.debug('Successfully connected to Cassandra cluster at %s', contact_points) return cluster, session except TypeError: pass except (ConnectionException, ConnectionShutdown, NoHostAvailable): log.error('Could not connect to Cassandra cluster at %s', contact_points) raise CommandExecutionError('ERROR: Could not connect to Cassandra cluster.') def cql_query(query, contact_points=None, port=None, cql_user=None, cql_pass=None): ''' Run a query on a Cassandra cluster and return a dictionary. :param query: The query to execute. :type query: str :param contact_points: The Cassandra cluster addresses, can either be a string or a list of IPs. :type contact_points: str | list[str] :param cql_user: The Cassandra user if authentication is turned on. :type cql_user: str :param cql_pass: The Cassandra user password if authentication is turned on. :type cql_pass: str :param port: The Cassandra cluster port, defaults to None. :type port: int :param params: The parameters for the query, optional. :type params: str :return: A dictionary from the return values of the query :rtype: list[dict] CLI Example: .. code-block:: bash salt 'cassandra-server' cassandra_cql.cql_query "SELECT * FROM users_by_name WHERE first_name = 'jane'" ''' try: cluster, session = _connect(contact_points=contact_points, port=port, cql_user=cql_user, cql_pass=cql_pass) except CommandExecutionError: log.critical('Could not get Cassandra cluster session.') raise except BaseException as e: log.critical('Unexpected error while getting Cassandra cluster session: %s', e) raise session.row_factory = dict_factory ret = [] # Cassandra changed their internal schema from v2 to v3 # If the query contains a dictionary sorted by versions # Find the query for the current cluster version. # https://issues.apache.org/jira/browse/CASSANDRA-6717 if isinstance(query, dict): cluster_version = version(contact_points=contact_points, port=port, cql_user=cql_user, cql_pass=cql_pass) match = re.match(r'^(\d+)\.(\d+)(?:\.(\d+))?', cluster_version) major, minor, point = match.groups() # try to find the specific version in the query dictionary # then try the major version # otherwise default to the highest version number try: query = query[cluster_version] except KeyError: query = query.get(major, max(query)) log.debug('New query is: %s', query) try: results = session.execute(query) except BaseException as e: log.error('Failed to execute query: %s\n reason: %s', query, e) msg = "ERROR: Cassandra query failed: {0} reason: {1}".format(query, e) raise CommandExecutionError(msg) if results: for result in results: values = {} for key, value in six.iteritems(result): # Salt won't return dictionaries with odd types like uuid.UUID if not isinstance(value, six.text_type): # Must support Cassandra collection types. # Namely, Cassandras set, list, and map collections. if not isinstance(value, (set, list, dict)): value = six.text_type(value) values[key] = value ret.append(values) return ret def cql_query_with_prepare(query, statement_name, statement_arguments, callback_errors=None, contact_points=None, port=None, cql_user=None, cql_pass=None, **kwargs): ''' Run a query on a Cassandra cluster and return a dictionary. This function should not be used asynchronously for SELECTs -- it will not return anything and we don't currently have a mechanism for handling a future that will return results. :param query: The query to execute. :type query: str :param statement_name: Name to assign the prepared statement in the __context__ dictionary :type statement_name: str :param statement_arguments: Bind parameters for the SQL statement :type statement_arguments: list[str] :param async: Run this query in asynchronous mode :type async: bool :param callback_errors: Function to call after query runs if there is an error :type callback_errors: Function callable :param contact_points: The Cassandra cluster addresses, can either be a string or a list of IPs. :type contact_points: str | list[str] :param cql_user: The Cassandra user if authentication is turned on. :type cql_user: str :param cql_pass: The Cassandra user password if authentication is turned on. :type cql_pass: str :param port: The Cassandra cluster port, defaults to None. :type port: int :param params: The parameters for the query, optional. :type params: str :return: A dictionary from the return values of the query :rtype: list[dict] CLI Example: .. code-block:: bash # Insert data asynchronously salt this-node cassandra_cql.cql_query_with_prepare "name_insert" "INSERT INTO USERS (first_name, last_name) VALUES (?, ?)" \ statement_arguments=['John','Doe'], asynchronous=True # Select data, should not be asynchronous because there is not currently a facility to return data from a future salt this-node cassandra_cql.cql_query_with_prepare "name_select" "SELECT * FROM USERS WHERE first_name=?" \ statement_arguments=['John'] ''' # Backward-compatibility with Python 3.7: "async" is a reserved word asynchronous = kwargs.get('async', False) try: cluster, session = _connect(contact_points=contact_points, port=port, cql_user=cql_user, cql_pass=cql_pass) except CommandExecutionError: log.critical('Could not get Cassandra cluster session.') raise except BaseException as e: log.critical('Unexpected error while getting Cassandra cluster session: %s', e) raise if statement_name not in __context__['cassandra_cql_prepared']: try: bound_statement = session.prepare(query) __context__['cassandra_cql_prepared'][statement_name] = bound_statement except BaseException as e: log.critical('Unexpected error while preparing SQL statement: %s', e) raise else: bound_statement = __context__['cassandra_cql_prepared'][statement_name] session.row_factory = dict_factory ret = [] try: if asynchronous: future_results = session.execute_async(bound_statement.bind(statement_arguments)) # future_results.add_callbacks(_async_log_errors) else: results = session.execute(bound_statement.bind(statement_arguments)) except BaseException as e: log.error('Failed to execute query: %s\n reason: %s', query, e) msg = "ERROR: Cassandra query failed: {0} reason: {1}".format(query, e) raise CommandExecutionError(msg) if not asynchronous and results: for result in results: values = {} for key, value in six.iteritems(result): # Salt won't return dictionaries with odd types like uuid.UUID if not isinstance(value, six.text_type): # Must support Cassandra collection types. # Namely, Cassandras set, list, and map collections. if not isinstance(value, (set, list, dict)): value = six.text_type(value) values[key] = value ret.append(values) # If this was a synchronous call, then we either have an empty list # because there was no return, or we have a return # If this was an asynchronous call we only return the empty list return ret def version(contact_points=None, port=None, cql_user=None, cql_pass=None): ''' Show the Cassandra version. :param contact_points: The Cassandra cluster addresses, can either be a string or a list of IPs. :type contact_points: str | list[str] :param cql_user: The Cassandra user if authentication is turned on. :type cql_user: str :param cql_pass: The Cassandra user password if authentication is turned on. :type cql_pass: str :param port: The Cassandra cluster port, defaults to None. :type port: int :return: The version for this Cassandra cluster. :rtype: str CLI Example: .. code-block:: bash salt 'minion1' cassandra_cql.version salt 'minion1' cassandra_cql.version contact_points=minion1 ''' query = '''select release_version from system.local limit 1;''' try: ret = cql_query(query, contact_points, port, cql_user, cql_pass) except CommandExecutionError: log.critical('Could not get Cassandra version.') raise except BaseException as e: log.critical('Unexpected error while getting Cassandra version: %s', e) raise return ret[0].get('release_version') def info(contact_points=None, port=None, cql_user=None, cql_pass=None): ''' Show the Cassandra information for this cluster. :param contact_points: The Cassandra cluster addresses, can either be a string or a list of IPs. :type contact_points: str | list[str] :param cql_user: The Cassandra user if authentication is turned on. :type cql_user: str :param cql_pass: The Cassandra user password if authentication is turned on. :type cql_pass: str :param port: The Cassandra cluster port, defaults to None. :type port: int :return: The information for this Cassandra cluster. :rtype: dict CLI Example: .. code-block:: bash salt 'minion1' cassandra_cql.info salt 'minion1' cassandra_cql.info contact_points=minion1 ''' query = '''select cluster_name, data_center, partitioner, host_id, rack, release_version, cql_version, schema_version, thrift_version from system.local limit 1;''' ret = {} try: ret = cql_query(query, contact_points, port, cql_user, cql_pass) except CommandExecutionError: log.critical('Could not list Cassandra info.') raise except BaseException as e: log.critical('Unexpected error while listing Cassandra info: %s', e) raise return ret def list_keyspaces(contact_points=None, port=None, cql_user=None, cql_pass=None): ''' List keyspaces in a Cassandra cluster. :param contact_points: The Cassandra cluster addresses, can either be a string or a list of IPs. :type contact_points: str | list[str] :param cql_user: The Cassandra user if authentication is turned on. :type cql_user: str :param cql_pass: The Cassandra user password if authentication is turned on. :type cql_pass: str :param port: The Cassandra cluster port, defaults to None. :type port: int :return: The keyspaces in this Cassandra cluster. :rtype: list[dict] CLI Example: .. code-block:: bash salt 'minion1' cassandra_cql.list_keyspaces salt 'minion1' cassandra_cql.list_keyspaces contact_points=minion1 port=9000 ''' query = { '2': 'select keyspace_name from system.schema_keyspaces;', '3': 'select keyspace_name from system_schema.keyspaces;', } ret = {} try: ret = cql_query(query, contact_points, port, cql_user, cql_pass) except CommandExecutionError: log.critical('Could not list keyspaces.') raise except BaseException as e: log.critical('Unexpected error while listing keyspaces: %s', e) raise return ret def list_column_families(keyspace=None, contact_points=None, port=None, cql_user=None, cql_pass=None): ''' List column families in a Cassandra cluster for all keyspaces or just the provided one. :param keyspace: The keyspace to provide the column families for, optional. :type keyspace: str :param contact_points: The Cassandra cluster addresses, can either be a string or a list of IPs. :type contact_points: str | list[str] :param cql_user: The Cassandra user if authentication is turned on. :type cql_user: str :param cql_pass: The Cassandra user password if authentication is turned on. :type cql_pass: str :param port: The Cassandra cluster port, defaults to None. :type port: int :return: The column families in this Cassandra cluster. :rtype: list[dict] CLI Example: .. code-block:: bash salt 'minion1' cassandra_cql.list_column_families salt 'minion1' cassandra_cql.list_column_families contact_points=minion1 salt 'minion1' cassandra_cql.list_column_families keyspace=system ''' where_clause = "where keyspace_name = '{0}'".format(keyspace) if keyspace else "" query = { '2': '''select columnfamily_name from system.schema_columnfamilies {0};'''.format(where_clause), '3': '''select column_name from system_schema.columns {0};'''.format(where_clause), } ret = {} try: ret = cql_query(query, contact_points, port, cql_user, cql_pass) except CommandExecutionError: log.critical('Could not list column families.') raise except BaseException as e: log.critical('Unexpected error while listing column families: %s', e) raise return ret def keyspace_exists(keyspace, contact_points=None, port=None, cql_user=None, cql_pass=None): ''' Check if a keyspace exists in a Cassandra cluster. :param keyspace The keyspace name to check for. :type keyspace: str :param contact_points: The Cassandra cluster addresses, can either be a string or a list of IPs. :type contact_points: str | list[str] :param cql_user: The Cassandra user if authentication is turned on. :type cql_user: str :param cql_pass: The Cassandra user password if authentication is turned on. :type cql_pass: str :param port: The Cassandra cluster port, defaults to None. :type port: int :return: The info for the keyspace or False if it does not exist. :rtype: dict CLI Example: .. code-block:: bash salt 'minion1' cassandra_cql.keyspace_exists keyspace=system ''' query = { '2': '''select keyspace_name from system.schema_keyspaces where keyspace_name = '{0}';'''.format(keyspace), '3': '''select keyspace_name from system_schema.keyspaces where keyspace_name = '{0}';'''.format(keyspace), } try: ret = cql_query(query, contact_points, port, cql_user, cql_pass) except CommandExecutionError: log.critical('Could not determine if keyspace exists.') raise except BaseException as e: log.critical('Unexpected error while determining if keyspace exists: %s', e) raise return True if ret else False def create_keyspace(keyspace, replication_strategy='SimpleStrategy', replication_factor=1, replication_datacenters=None, contact_points=None, port=None, cql_user=None, cql_pass=None): ''' Create a new keyspace in Cassandra. :param keyspace: The keyspace name :type keyspace: str :param replication_strategy: either `SimpleStrategy` or `NetworkTopologyStrategy` :type replication_strategy: str :param replication_factor: number of replicas of data on multiple nodes. not used if using NetworkTopologyStrategy :type replication_factor: int :param replication_datacenters: string or dict of datacenter names to replication factors, required if using NetworkTopologyStrategy (will be a dict if coming from state file). :type replication_datacenters: str | dict[str, int] :param contact_points: The Cassandra cluster addresses, can either be a string or a list of IPs. :type contact_points: str | list[str] :param cql_user: The Cassandra user if authentication is turned on. :type cql_user: str :param cql_pass: The Cassandra user password if authentication is turned on. :type cql_pass: str :param port: The Cassandra cluster port, defaults to None. :type port: int :return: The info for the keyspace or False if it does not exist. :rtype: dict CLI Example: .. code-block:: bash # CLI Example: salt 'minion1' cassandra_cql.create_keyspace keyspace=newkeyspace salt 'minion1' cassandra_cql.create_keyspace keyspace=newkeyspace replication_strategy=NetworkTopologyStrategy \ replication_datacenters='{"datacenter_1": 3, "datacenter_2": 2}' ''' existing_keyspace = keyspace_exists(keyspace, contact_points, port) if not existing_keyspace: # Add the strategy, replication_factor, etc. replication_map = { 'class': replication_strategy } if replication_datacenters: if isinstance(replication_datacenters, six.string_types): try: replication_datacenter_map = salt.utils.json.loads(replication_datacenters) replication_map.update(**replication_datacenter_map) except BaseException: # pylint: disable=W0703 log.error("Could not load json replication_datacenters.") return False else: replication_map.update(**replication_datacenters) else: replication_map['replication_factor'] = replication_factor query = '''create keyspace {0} with replication = {1} and durable_writes = true;'''.format(keyspace, replication_map) try: cql_query(query, contact_points, port, cql_user, cql_pass) except CommandExecutionError: log.critical('Could not create keyspace.') raise except BaseException as e: log.critical('Unexpected error while creating keyspace: %s', e) raise def list_users(contact_points=None, port=None, cql_user=None, cql_pass=None): ''' List existing users in this Cassandra cluster. :param contact_points: The Cassandra cluster addresses, can either be a string or a list of IPs. :type contact_points: str | list[str] :param port: The Cassandra cluster port, defaults to None. :type port: int :param cql_user: The Cassandra user if authentication is turned on. :type cql_user: str :param cql_pass: The Cassandra user password if authentication is turned on. :type cql_pass: str :return: The list of existing users. :rtype: dict CLI Example: .. code-block:: bash salt 'minion1' cassandra_cql.list_users salt 'minion1' cassandra_cql.list_users contact_points=minion1 ''' query = "list users;" ret = {} try: ret = cql_query(query, contact_points, port, cql_user, cql_pass) except CommandExecutionError: log.critical('Could not list users.') raise except BaseException as e: log.critical('Unexpected error while listing users: %s', e) raise return ret def create_user(username, password, superuser=False, contact_points=None, port=None, cql_user=None, cql_pass=None): ''' Create a new cassandra user with credentials and superuser status. :param username: The name of the new user. :type username: str :param password: The password of the new user. :type password: str :param superuser: Is the new user going to be a superuser? default: False :type superuser: bool :param contact_points: The Cassandra cluster addresses, can either be a string or a list of IPs. :type contact_points: str | list[str] :param cql_user: The Cassandra user if authentication is turned on. :type cql_user: str :param cql_pass: The Cassandra user password if authentication is turned on. :type cql_pass: str :param port: The Cassandra cluster port, defaults to None. :type port: int :return: :rtype: CLI Example: .. code-block:: bash salt 'minion1' cassandra_cql.create_user username=joe password=secret salt 'minion1' cassandra_cql.create_user username=joe password=secret superuser=True salt 'minion1' cassandra_cql.create_user username=joe password=secret superuser=True contact_points=minion1 ''' superuser_cql = 'superuser' if superuser else 'nosuperuser' query = '''create user if not exists {0} with password '{1}' {2};'''.format(username, password, superuser_cql) log.debug("Attempting to create a new user with username=%s superuser=%s", username, superuser_cql) # The create user query doesn't actually return anything if the query succeeds. # If the query fails, catch the exception, log a messange and raise it again. try: cql_query(query, contact_points, port, cql_user, cql_pass) except CommandExecutionError: log.critical('Could not create user.') raise except BaseException as e: log.critical('Unexpected error while creating user: %s', e) raise return True def create_role(username, password, superuser=False, login=False, contact_points=None, port=None, cql_user=None, cql_pass=None): ''' Create a new cassandra role with credentials and superuser status. :param username: The name of the new user. :type username: str :param password: The password of the new user. :type password: str :param superuser: Is the new role going to be a superuser? default: False :type superuser: bool :param login: Is the new role going to be allowed to log in? default: False :type superuser: bool :param contact_points: The Cassandra cluster addresses, can either be a string or a list of IPs. :type contact_points: str | list[str] :param cql_user: The Cassandra user if authentication is turned on. :type cql_user: str :param cql_pass: The Cassandra user password if authentication is turned on. :type cql_pass: str :param port: The Cassandra cluster port, defaults to None. :type port: int :return: :rtype: CLI Example: .. code-block:: bash salt 'minion1' cassandra_cql.create_role username=joe password=secret salt 'minion1' cassandra_cql.create_role username=joe password=secret superuser=True salt 'minion1' cassandra_cql.create_role username=joe password=secret superuser=True login=True salt 'minion1' cassandra_cql.create_role username=joe password=secret superuser=True login=True contact_points=minion1 ''' superuser_cql = 'superuser = true' if superuser else 'superuser = false' login_cql = 'login = true' if login else 'login = false' query = '''create role if not exists {0} with password '{1}' and {2} and {3} ;'''.format(username, password, superuser_cql, login_cql) log.debug("Attempting to create a new role with username=%s superuser=%s login=%s", username, superuser, login) # The create role query doesn't actually return anything if the query succeeds. # If the query fails, catch the exception, log a messange and raise it again. try: cql_query(query, contact_points, port, cql_user, cql_pass) except CommandExecutionError: log.critical('Could not create role.') raise except BaseException as e: log.critical('Unexpected error while creating role: %s', e) raise return True def list_permissions(username=None, resource=None, resource_type='keyspace', permission=None, contact_points=None, port=None, cql_user=None, cql_pass=None): ''' List permissions. :param username: The name of the user to list permissions for. :type username: str :param resource: The resource (keyspace or table), if None, permissions for all resources are listed. :type resource: str :param resource_type: The resource_type (keyspace or table), defaults to 'keyspace'. :type resource_type: str :param permission: A permission name (e.g. select), if None, all permissions are listed. :type permission: str :param contact_points: The Cassandra cluster addresses, can either be a string or a list of IPs. :type contact_points: str | list[str] :param cql_user: The Cassandra user if authentication is turned on. :type cql_user: str :param cql_pass: The Cassandra user password if authentication is turned on. :type cql_pass: str :param port: The Cassandra cluster port, defaults to None. :type port: int :return: Dictionary of permissions. :rtype: dict CLI Example: .. code-block:: bash salt 'minion1' cassandra_cql.list_permissions salt 'minion1' cassandra_cql.list_permissions username=joe resource=test_keyspace permission=select salt 'minion1' cassandra_cql.list_permissions username=joe resource=test_table resource_type=table \ permission=select contact_points=minion1 ''' keyspace_cql = "{0} {1}".format(resource_type, resource) if resource else "all keyspaces" permission_cql = "{0} permission".format(permission) if permission else "all permissions" query = "list {0} on {1}".format(permission_cql, keyspace_cql) if username: query = "{0} of {1}".format(query, username) log.debug("Attempting to list permissions with query '%s'", query) ret = {} try: ret = cql_query(query, contact_points, port, cql_user, cql_pass) except CommandExecutionError: log.critical('Could not list permissions.') raise except BaseException as e: log.critical('Unexpected error while listing permissions: %s', e) raise return ret def grant_permission(username, resource=None, resource_type='keyspace', permission=None, contact_points=None, port=None, cql_user=None, cql_pass=None): ''' Grant permissions to a user. :param username: The name of the user to grant permissions to. :type username: str :param resource: The resource (keyspace or table), if None, permissions for all resources are granted. :type resource: str :param resource_type: The resource_type (keyspace or table), defaults to 'keyspace'. :type resource_type: str :param permission: A permission name (e.g. select), if None, all permissions are granted. :type permission: str :param contact_points: The Cassandra cluster addresses, can either be a string or a list of IPs. :type contact_points: str | list[str] :param cql_user: The Cassandra user if authentication is turned on. :type cql_user: str :param cql_pass: The Cassandra user password if authentication is turned on. :type cql_pass: str :param port: The Cassandra cluster port, defaults to None. :type port: int :return: :rtype: CLI Example: .. code-block:: bash salt 'minion1' cassandra_cql.grant_permission salt 'minion1' cassandra_cql.grant_permission username=joe resource=test_keyspace permission=select salt 'minion1' cassandra_cql.grant_permission username=joe resource=test_table resource_type=table \ permission=select contact_points=minion1 ''' permission_cql = "grant {0}".format(permission) if permission else "grant all permissions" resource_cql = "on {0} {1}".format(resource_type, resource) if resource else "on all keyspaces" query = "{0} {1} to {2}".format(permission_cql, resource_cql, username) log.debug("Attempting to grant permissions with query '%s'", query) try: cql_query(query, contact_points, port, cql_user, cql_pass) except CommandExecutionError: log.critical('Could not grant permissions.') raise except BaseException as e: log.critical('Unexpected error while granting permissions: %s', e) raise return True