Gets configuration on how to connect to Consul from the environment.
    :return: the configuration derived from the environment
    :raises KeyError: if a required environment variable has not been set
162278
def get_consul_configuration_from_environment() -> ConsulConfiguration:
    
    address = os.environ[CONSUL_ADDRESS_ENVIRONMENT_VARIABLE]
    if "://" in address:
        raise EnvironmentError(f"Invalid host: {address}. Do not specify scheme in host - set that in "
                               f"{CONSUL_SCHEME_ENVIRONMENT_VARIABLE}")

    host_port_split = address.split(":")
    host = host_port_split[0]
    if len(host_port_split) == 1:
        _get_logger().info(
            f"No port specified in address read from the environment - using default port: {DEFAULT_CONSUL_PORT}")
        port = DEFAULT_CONSUL_PORT
    else:
        port = host_port_split[1]

    return ConsulConfiguration(
        host=host,
        port=port,
        token=os.environ.get(CONSUL_TOKEN_ENVIRONMENT_VARIABLE, DEFAULT_CONSUL_TOKEN),
        scheme=os.environ.get(CONSUL_SCHEME_ENVIRONMENT_VARIABLE, DEFAULT_CONSUL_SCHEME),
        datacentre=os.environ.get(CONSUL_DATACENTRE_ENVIRONMENT_VARIABLE, DEFAULT_CONSUL_DATACENTRE),
        verify=os.environ.get(CONSUL_VERIFY_ENVIRONMENT_VARIABLE, DEFAULT_CONSUL_VERIFY),
        certificate=os.environ.get(CONSUL_CERTIFICATE_ENVIRONMENT_VARIABLE, DEFAULT_CONSUL_CERTIFICATE))
356377
def obtain_hosting_device_credentials_from_config():
    
    cred_dict = get_specific_config('cisco_hosting_device_credential')
    attr_info = {
        'name': {'allow_post': True, 'allow_put': True,
                 'validate': {'type:string': None}, 'is_visible': True,
                 'default': ''},
        'description': {'allow_post': True, 'allow_put': True,
                        'validate': {'type:string': None},
                        'is_visible': True, 'default': ''},
        'user_name': {'allow_post': True, 'allow_put': True,
                      'validate': {'type:string': None},
                      'is_visible': True, 'default': ''},
        'password': {'allow_post': True, 'allow_put': True,
                     'validate': {'type:string': None},
                     'is_visible': True, 'default': ''},
        'type': {'allow_post': True, 'allow_put': True,
                 'validate': {'type:string': None}, 'is_visible': True,
                 'default': ''}}
    credentials = {}
    for cred_uuid, kv_dict in cred_dict.items():
        # ensure cred_uuid is properly formatted
        cred_uuid = uuidify(cred_uuid)
        verify_resource_dict(kv_dict, True, attr_info)
        credentials[cred_uuid] = kv_dict
    return credentials
399565
def get(self, key, env=None):
        
        if env is None:
            env = self.environment
        try:
            ret = self._settings[env][key]
        except KeyError:
            ret = None
        if ret is None:
            # See if it's set in the environment
            if key == "identity_class":
                # This is defined via the identity_type
                env_var = self.env_dct.get("identity_type")
                ityp = os.environ.get(env_var)
                if ityp:
                    return _import_identity(ityp)
            else:
                env_var = self.env_dct.get(key)
            if env_var is not None:
                ret = os.environ.get(env_var)
        return ret
1043447
def cdn_get_conf(self, cname, environment):
        
        response = self.client.service.cdn_get_conf(cname, environment)
        cdn_config = CotendoCDN(response)
        return cdn_config
719968
def get_configuration():
    
    configuration = {
        "get_object_function": None,
        "hcard_path": "/hcard/users/",
        "nodeinfo2_function": None,
        "process_payload_function": None,
        "search_path": None,
        # TODO remove or default to True once AP support is more ready
        "activitypub": False,
    }
    configuration.update(settings.FEDERATION)
    if not all([
        "get_private_key_function" in configuration,
        "get_profile_function" in configuration,
        "base_url" in configuration,
    ]):
        raise ImproperlyConfigured("Missing required FEDERATION settings, please check documentation.")
    return configuration
627617
def _get_config(**kwargs):
    '''
    
    '''
    config = {
        'box_type': 'sealedbox',
        'sk': None,
        'sk_file': os.path.join(kwargs['opts'].get('pki_dir'), 'master/nacl'),
        'pk': None,
        'pk_file': os.path.join(kwargs['opts'].get('pki_dir'), 'master/nacl.pub'),
    }

    config_key = '{0}.config'.format(__virtualname__)
    try:
        config.update(__salt__['config.get'](config_key, {}))
    except (NameError, KeyError) as e:
        # likely using salt-run so fallback to __opts__
        config.update(kwargs['opts'].get(config_key, {}))
    # pylint: disable=C0201
    for k in set(config.keys()) & set(kwargs.keys()):
        config[k] = kwargs[k]
    return config
281010
def get_config(self, retrieve="all"):
        """"""
        get_startup = retrieve == "all" or retrieve == "startup"
        get_running = retrieve == "all" or retrieve == "running"
        get_candidate = (retrieve == "all" or retrieve == "candidate") and self.config_session

        if retrieve == "all":
            commands = ['show startup-config',
                        'show running-config']

            if self.config_session:
                commands.append('show session-config named {}'.format(self.config_session))

            output = self.device.run_commands(commands, encoding="text")
            return {
                'startup': py23_compat.text_type(output[0]['output']) if get_startup else u"",
                'running': py23_compat.text_type(output[1]['output']) if get_running else u"",
                'candidate': py23_compat.text_type(output[2]['output']) if get_candidate else u"",
            }
        elif get_startup or get_running:
            commands = ['show {}-config'.format(retrieve)]
            output = self.device.run_commands(commands, encoding="text")
            return {
                'startup': py23_compat.text_type(output[0]['output']) if get_startup else u"",
                'running': py23_compat.text_type(output[0]['output']) if get_running else u"",
                'candidate': "",
            }
        elif get_candidate:
            commands = ['show session-config named {}'.format(self.config_session)]
            output = self.device.run_commands(commands, encoding="text")
            return {
                'startup': "",
                'running': "",
                'candidate': py23_compat.text_type(output[0]['output']),
            }
        elif retrieve == "candidate":
            # If we get here it means that we want the candidate but there is none.
            return {
                'startup': "",
                'running': "",
                'candidate': "",
            }
        else:
            raise Exception("Wrong retrieve filter: {}".format(retrieve))
504772
def get_aliyun_config(name, default=None):
    '''
    
    '''
    config = os.environ.get(name, getattr(settings, name, default))
    if config is not None:
        if isinstance(config, str):
            return config.strip()
        else:
            return config
    else:
        raise ImproperlyConfigured(
            'Can not get config for {} either in environment'
            'variable or in settings.py'.format(name))
1311708
def get_default_config(self):
        
        config = super(ProcessCollector, self).get_default_config()
        config.update({
            'use_sudo':     False,
            'sudo_cmd':     self.find_binary('/usr/bin/sudo'),
        })
        return config
409776
def consul_fetch(client, path):
    '''
    
    '''
    # Unless the root path is blank, it needs a trailing slash for
    # the kv get from Consul to work as expected
    return client.kv.get('' if not path else path.rstrip('/') + '/', recurse=True)
786930
def get_config(basedir, files):
    
    config_details = config.find(
        basedir, files,
        environment.Environment.from_env_file(basedir))

    return config.load(config_details)
1365438
def _get_config(self, host, port, unix_socket, auth, config_key):
        

        client = self._client(host, port, unix_socket, auth)
        if client is None:
            return None

        config_value = client.config_get(config_key)
        del client
        return config_value
1360290
def get_config(self, hostname):
        
        version, config = self._get(
            self.associations.get(hostname)
        )
        return config
1204727
def get_proxies(self):
        
        # Get proxy from ENV or Config
        proxies = None
        proxy_auth = None
        no_proxy = os.environ.get('NO_PROXY')
        logger.debug("NO PROXY: %s", no_proxy)

        # CONF PROXY TAKES PRECEDENCE OVER ENV PROXY
        conf_proxy = self.config.proxy
        if ((conf_proxy is not None and
             conf_proxy.lower() != 'None'.lower() and
             conf_proxy != "")):
            if '@' in conf_proxy:
                scheme = conf_proxy.split(':')[0] + '://'
                logger.debug("Proxy Scheme: %s", scheme)
                location = conf_proxy.split('@')[1]
                logger.debug("Proxy Location: %s", location)
                username = conf_proxy.split(
                    '@')[0].split(':')[1].replace('/', '')
                logger.debug("Proxy User: %s", username)
                password = conf_proxy.split('@')[0].split(':')[2]
                proxy_auth = requests.auth._basic_auth_str(username, password)
                conf_proxy = scheme + location
            logger.debug("CONF Proxy: %s", conf_proxy)
            proxies = {"https": conf_proxy}

        # HANDLE NO PROXY CONF PROXY EXCEPTION VERBIAGE
        if no_proxy and conf_proxy:
            logger.debug("You have environment variable NO_PROXY set "
                         "as well as 'proxy' set in your configuration file. "
                         "NO_PROXY environment variable will be ignored.")

        # IF NO CONF PROXY, GET ENV PROXY AND NO PROXY
        if proxies is None:
            env_proxy = os.environ.get('HTTPS_PROXY')
            if env_proxy:
                if '@' in env_proxy:
                    scheme = env_proxy.split(':')[0] + '://'
                    logger.debug("Proxy Scheme: %s", scheme)
                    location = env_proxy.split('@')[1]
                    logger.debug("Proxy Location: %s", location)
                    username = env_proxy.split('@')[0].split(':')[1].replace('/', '')
                    logger.debug("Proxy User: %s", username)
                    password = env_proxy.split('@')[0].split(':')[2]
                    proxy_auth = requests.auth._basic_auth_str(username, password)
                    env_proxy = scheme + location
                logger.debug("ENV Proxy: %s", env_proxy)
                proxies = {"https": env_proxy}
            if no_proxy:
                insights_service_host = urlparse(self.base_url).hostname
                logger.debug('Found NO_PROXY set. Checking NO_PROXY %s against base URL %s.', no_proxy, insights_service_host)
                for no_proxy_host in no_proxy.split(','):
                    logger.debug('Checking %s against %s', no_proxy_host, insights_service_host)
                    if no_proxy_host == '*':
                        proxies = None
                        proxy_auth = None
                        logger.debug('Found NO_PROXY asterisk(*) wildcard, disabling all proxies.')
                        break
                    elif no_proxy_host.startswith('.') or no_proxy_host.startswith('*'):
                        if insights_service_host.endswith(no_proxy_host.replace('*', '')):
                            proxies = None
                            proxy_auth = None
                            logger.debug('Found NO_PROXY range %s matching %s', no_proxy_host, insights_service_host)
                            break
                    elif no_proxy_host == insights_service_host:
                        proxies = None
                        proxy_auth = None
                        logger.debug('Found NO_PROXY %s exactly matching %s', no_proxy_host, insights_service_host)
                        break

        self.proxies = proxies
        self.proxy_auth = proxy_auth
44469
def get_config():
    
    if session.config is None:
        path = session.default_config_path
        if os.path.isfile(path):
            logging.info("LOADING FROM: {}".format(path))
            session.config = load_config(path)
        else:
            session.config = Config()
            logging.info("using default session: {}, path does not exist: {}".format(session, path))
    else:
        logging.info("Using pre-loaded object: {}".format(session.config))
    return session.config
140295
def main(cli_arguments: List[str]):
    
    cli_configuration: CliConfiguration
    try:
        cli_configuration = parse_cli_configuration(cli_arguments)
    except InvalidCliArgumentError as e:
        logger.error(e)
        exit(INVALID_CLI_ARGUMENT_EXIT_CODE)
    except SystemExit as e:
        exit(e.code)

    if cli_configuration.log_verbosity:
        logging.getLogger(PACKAGE_NAME).setLevel(cli_configuration.log_verbosity)

    consul_configuration: ConsulConfiguration
    try:
        consul_configuration = get_consul_configuration_from_environment()
    except KeyError as e:
        logger.error(f"Cannot connect to Consul - the environment variable {e.args[0]} must be set")
        exit(MISSING_REQUIRED_ENVIRONMENT_VARIABLE_EXIT_CODE)
    except InvalidEnvironmentVariableError as e:
        logger.error(e)
        exit(INVALID_ENVIRONMENT_VARIABLE_EXIT_CODE)

    lock_manager: ConsulLockManager
    try:
        lock_manager = ConsulLockManager(
            consul_configuration=consul_configuration, session_ttl_in_seconds=cli_configuration.session_ttl)
    except InvalidSessionTtlValueError as e:
        logger.error(e)
        exit(INVALID_SESSION_TTL_EXIT_CODE)

    try:
        {
            CliLockConfiguration: _acquire_lock_and_exit,
            CliLockAndExecuteConfiguration: _acquire_lock_and_execute,
            CliUnlockConfiguration: _release_lock
        }[type(cli_configuration)](lock_manager, cli_configuration)
    except PermissionDeniedConsulError as e:
        error_message = f"Invalid credentials - are you sure you have set {CONSUL_TOKEN_ENVIRONMENT_VARIABLE} " \
                        f"correctly?"
        logger.debug(e)
        logger.error(error_message)
        exit(PERMISSION_DENIED_EXIT_CODE)
    except DoubleSlashKeyError as e:
        logger.debug(e)
        logger.error(f"Double slashes \"//\" in keys get converted into single slashes \"/\" - please use a "
                     f"single slash if this is intended: {cli_configuration.key}")
        exit(INVALID_KEY_EXIT_CODE)
    except NonNormalisedKeyError as e:
        logger.debug(e)
        logger.error(f"Key paths must be normalised - use \"{normpath(e.key)}\" if this key was intended: "
                     f"{cli_configuration.key}")
        exit(INVALID_KEY_EXIT_CODE)
617631
def _setup(self, name=None):
        
        envvar = self.__dict__['env_var']
        if envvar:
            settings_file = os.environ.get(envvar)
        else:
            settings_file = self.__dict__['file_path']

        if not settings_file:
            msg = ("Requested settings, but none can be obtained for the envvar."
                   "Since no config filepath can be obtained, a default config "
                   "will be used.")
            logger.error(msg)
            raise OSError(msg)

        self._wrapped = Settings(settings_file)