Read credentials from anywhere (CSV, Environment, Instance metadata, config/credentials)

    :param profile_name:
    :param csv_file:
    :param mfa_serial_arg:
    :param mfa_code:
    :param force_init:
    :param role_session_name:

    :return:
970033
def read_creds(profile_name, csv_file = None, mfa_serial_arg = None, mfa_code = None, force_init = False,
               role_session_name = 'opinel'):
    
    first_sts_session = False
    source_profile = None
    role_mfa_serial = None
    expiration = None
    credentials = init_creds()
    role_arn, external_id = read_profile_from_environment_variables()
    if csv_file:
        # Read credentials from a CSV file that was provided
        credentials['AccessKeyId'], credentials['SecretAccessKey'], credentials['SerialNumber'] = \
            read_creds_from_csv(csv_file)
    elif profile_name == 'default':
        # Try reading credentials from environment variables (Issue #11) if the profile name is 'default'
        credentials = read_creds_from_environment_variables()
    if ('AccessKeyId' not in credentials or not credentials['AccessKeyId']) \
            and not csv_file and profile_name == 'default':
        ec2_credentials = read_creds_from_ec2_instance_metadata()
        if ec2_credentials:
            credentials = ec2_credentials
        else:
            ecs_credentials = read_creds_from_ecs_container_metadata()
            if ecs_credentials:
                credentials = ecs_credentials
        # TODO support lambda
    if role_arn or (not credentials['AccessKeyId'] and not csv_file):
        # Lookup if a role is defined in ~/.aws/config
        if not role_arn:
            role_arn, source_profile, role_mfa_serial, external_id = read_profile_from_aws_config_file(profile_name)
        # Scout2 issue 237 - credentials file may be used to configure role-based profiles...
        if not role_arn:
            role_arn, source_profile, role_mfa_serial, external_id = \
                read_profile_from_aws_config_file(profile_name, config_file = aws_credentials_file)
        if role_arn:
            # Lookup cached credentials
            try:
                cached_credentials_filename = get_cached_credentials_filename(profile_name, role_arn)
                with open(cached_credentials_filename, 'rt') as f:
                    assume_role_data = json.load(f)
                    oldcred = credentials
                    credentials = assume_role_data['Credentials']
                    expiration = dateutil.parser.parse(credentials['Expiration'])
                    expiration = expiration.replace(tzinfo=None)
                    current = datetime.datetime.utcnow()
                    if expiration < current:
                        print('Role\'s credentials have expired on %s' % credentials['Expiration'])
                        credentials = oldcred
            except Exception as e:
                pass
            if not expiration or expiration < current or credentials['AccessKeyId'] == None:
                if source_profile:
                    credentials = read_creds(source_profile)
                if role_mfa_serial:
                    credentials['SerialNumber'] = role_mfa_serial
                    # Auto prompt for a code...
                    if not mfa_code:
                        credentials['TokenCode'] = prompt_4_mfa_code()
                if external_id:
                    credentials['ExternalId'] = external_id
                credentials = assume_role(profile_name, credentials, role_arn, role_session_name)
        # Read from ~/.aws/credentials
        else:
            credentials = read_creds_from_aws_credentials_file(profile_name)
            if credentials['SessionToken']:
                if 'Expiration' in credentials and credentials['Expiration']:
                    expiration = dateutil.parser.parse(credentials['Expiration'])
                    expiration = expiration.replace(tzinfo=None)
                    current = datetime.datetime.utcnow()
                    if expiration < current:
                        printInfo('Saved STS credentials expired on %s' % credentials['Expiration'])
                        force_init = True
                else:
                    force_init = True
                    sts_credentials = credentials
            else:
                first_sts_session = True
            if force_init or (mfa_serial_arg and mfa_code):
                credentials = read_creds_from_aws_credentials_file(profile_name if first_sts_session
                                                                   else '%s-nomfa' % profile_name)
                if not credentials['AccessKeyId']:
                    printInfo('Warning: Unable to determine STS token expiration; later API calls may fail.')
                    credentials = sts_credentials
                else:
                    if mfa_serial_arg:
                        credentials['SerialNumber'] = mfa_serial_arg
                    if mfa_code:
                        credentials['TokenCode'] = mfa_code
                    if 'AccessKeyId' in credentials and credentials['AccessKeyId']:
                        credentials = init_sts_session(profile_name, credentials)
    # If we don't have valid creds by now, print an error message
    if 'AccessKeyId' not in credentials or credentials['AccessKeyId'] == None or \
            'SecretAccessKey' not in credentials or credentials['SecretAccessKey'] == None:
        printError('Error: could not find AWS credentials. Use the --help option for more information.')
    if not 'AccessKeyId' in credentials:
        credentials = { 'AccessKeyId': None }
    return credentials
360940
def get_credentials(*, scopes):
    
    credential_dir = os.path.join(HOME_DIR, ".cache", __package__, "credentials")
    if not os.path.exists(credential_dir):
        os.makedirs(credential_dir)
    credential_path = os.path.join(credential_dir, "googleapis.json")

    store = Storage(credential_path)
    credentials = store.get()

    # see https://developers.google.com/api-client-library/python/auth/web-app
    # kw: "incremental scopes"
    if not credentials or credentials.invalid or not credentials.has_scopes(scopes):
        flow = client.flow_from_clientsecrets(GOOGLE_SECRETS, scopes)
        flow.user_agent = "Bonobo ETL (https://www.bonobo-project.org/)"
        flags = argparser.parse_args(["--noauth_local_webserver"])
        credentials = tools.run_flow(flow, store, flags)
        print("Storing credentials to " + credential_path)
    return credentials
947196
def _get_credentials(server=None,
                     username=None,
                     password=None):
    '''
    
    '''
    jira_cfg = __salt__['config.merge']('jira', default={})
    if not server:
        server = jira_cfg.get('server')
    if not username:
        username = jira_cfg.get('username')
    if not password:
        password = jira_cfg.get('password')
    return server, username, password
1022543
def _load_yaml_credentials(filename=None, yaml_key=None):
    
    try:
        with open(os.path.expanduser(filename)) as f:
            search_creds = yaml.safe_load(f)[yaml_key]
    except FileNotFoundError:
        logger.error("cannot read file {}".format(filename))
        search_creds = {}
    except KeyError:
        logger.error("{} is missing the provided key: {}"
                     .format(filename, yaml_key))
        search_creds = {}

    return search_creds
694078
def get_credentials(options, environment):
    
    if options['--username'] or options['--auth']:
        if not options['--username']:
            options['<username>'] = lib.prompt("Please enter the username for %s..." % environment)
        if not options['--password']:
            options['<password>'] = lib.prompt("Please enter the password for %s..." % environment, secret=True)
    return options
731260
def list_credentials_by_name(type_name):
  
  accounts = get_all_external_accounts(api, type_name)
  account_names = [account.name for account in accounts]
  print ("List of credential names for '{0}': [{1}]".format(
    type_name, COMMA_WITH_SPACE.join(map(str, account_names))))
1215336
def get_credentials(self):
        
        return Credentials(access_key=self.aws_access_key_id,
                           secret_key=self.aws_secret_access_key,
                           token=self.aws_session_token)
932123
def get_references(profile_path, role, profile_name, server):
    
    references_for_profile = server.conn.References(
        ObjectName=profile_path,
        ResultClass="CIM_ReferencedProfile",
        Role=role)

    if VERBOSE:
        print('References for profile=%s, path=%s, ResultClass='
              'CIM_ReferencedProfile, Role=%s' % (profile_name, profile_path,
                                                  role))
        for ref in references_for_profile:
            print('Reference for %s get_role=%s cn=%s\n   antecedent=%s\n   '
                  'dependent=%s' % (profile_name, role, ref.classname,
                                    ref['Antecedent'], ref['Dependent']))

    return references_for_profile
49839
def get_credentials(username=None, password=None, netrc=None, use_keyring=False):
    
    if netrc:
        path = None if netrc is True else netrc
        return authenticate_through_netrc(path)

    if not username:
        raise CredentialsError(
            'Please provide a username with the -u option, '
            'or a .netrc file with the -n option.')

    if not password and use_keyring:
        password = keyring.get_password(KEYRING_SERVICE_NAME, username)

    if not password:
        password = getpass.getpass('Coursera password for {0}: '.format(username))
        if use_keyring:
            keyring.set_password(KEYRING_SERVICE_NAME, username, password)

    return username, password
28225
def _get_conn(key=None,
              keyid=None,
              profile=None,
              region=None,
              **kwargs):
    '''
    
    '''
    client = None
    if profile:
        if isinstance(profile, six.string_types):
            if profile in __pillar__:
                profile = __pillar__[profile]
            elif profile in __opts__:
                profile = __opts__[profile]
    elif key or keyid or region:
        profile = {}
        if key:
            profile['key'] = key
        if keyid:
            profile['keyid'] = keyid
        if region:
            profile['region'] = region

    if isinstance(profile, dict):
        if 'region' in profile:
            profile['region_name'] = profile['region']
            profile.pop('region', None)
        if 'key' in profile:
            profile['aws_secret_access_key'] = profile['key']
            profile.pop('key', None)
        if 'keyid' in profile:
            profile['aws_access_key_id'] = profile['keyid']
            profile.pop('keyid', None)

        client = boto3.client('efs', **profile)
    else:
        client = boto3.client('efs')

    return client
748706
def profile_option(f):
    
    def callback(ctx, param, value):
        state = ctx.ensure_object(Context)
        state.profile = value
        return value

    return click.option('--profile',
                        expose_value=False,
                        help='Select a specific profile from your credential file to get AWS credentials.',
                        callback=callback)(f)
971019
def Credentials(self):
		

		return(clc.v2.API.Call('GET','servers/%s/%s/credentials' % (self.alias,self.name),session=self.session))
1220969
def set_credentials(username, api_key=None, password=None, region=None,
        tenant_id=None, authenticate=True):
    
    global regions, services
    pw_key = password or api_key
    region = _safe_region(region)
    tenant_id = tenant_id or settings.get("tenant_id")
    identity.set_credentials(username=username, password=pw_key,
            tenant_id=tenant_id, region=region, authenticate=authenticate)
    regions = tuple(identity.regions)
    services = tuple(identity.services.keys())
    connect_to_services(region=region)
277759
def get_profile(sqshrc="~/.sqshrc", connector='Sybase',
                hostname=None, username=None, password=None):
    
    if connector == 'Sybase':
        shost, suser, spass = None, None, None
        _ = lambda x: x.split("=")[-1].translate(None, "\"'").strip()
        sqshrc = op.expanduser(sqshrc)
        if op.exists(sqshrc):
            for row in open(sqshrc):
                row = row.strip()
                if not row.startswith("\\set") or "prompt" in row:
                    continue
                if "password" in row:
                    spass = _(row)
                if "hostname" in row:
                    shost = _(row)
                if "username" in row:
                    suser = _(row)
        else:
            print("[warning] file `{0}` not found".format(sqshrc), file=sys.stderr)

        if suser and spass:
            username, password = suser, spass
        if shost:
            hostname = shost

    dhost, duser, dpass = db_defaults(connector=connector)
    if not password:
        username, password = duser, dpass
    elif not username:
        username = getusername()

    if not hostname:
        hostname = dhost

    return hostname, username, password
478073
def ServiceAccountCredentialsFromFile(filename, scopes, user_agent=None):
    """"""
    filename = os.path.expanduser(filename)
    # We have two options, based on our version of oauth2client.
    if oauth2client.__version__ > '1.5.2':
        # oauth2client >= 2.0.0
        credentials = (
            service_account.ServiceAccountCredentials.from_json_keyfile_name(
                filename, scopes=scopes))
        if credentials is not None:
            if user_agent is not None:
                credentials.user_agent = user_agent
        return credentials
    else:
        # oauth2client < 2.0.0
        with open(filename) as keyfile:
            service_account_info = json.load(keyfile)
        account_type = service_account_info.get('type')
        if account_type != oauth2client.client.SERVICE_ACCOUNT:
            raise exceptions.CredentialsError(
                'Invalid service account credentials: %s' % (filename,))
        # pylint: disable=protected-access
        credentials = service_account._ServiceAccountCredentials(
            service_account_id=service_account_info['client_id'],
            service_account_email=service_account_info['client_email'],
            private_key_id=service_account_info['private_key_id'],
            private_key_pkcs8_text=service_account_info['private_key'],
            scopes=scopes, user_agent=user_agent)
        # pylint: enable=protected-access
        return credentials
723025
def reread(self):
        
        logger.debug("Loading credentials from %s",
                     os.path.abspath(self.creds_filename))
        creds = {}
        try:
            with self.open_creds() as fp:
                creds = yaml.safe_load(fp)
        except IOError:
            logger.info("No credentials file found at %s",
                        os.path.abspath(self.creds_filename))
        except:
            logger.exception("Error loading credentials file")
        if creds != self.creds:
            self.creds = creds
            return True
        return False
1258206
def get_aws_secrets_from_file(credentials_file):  # type: (str) -> Set[str]
    
    aws_credentials_file_path = os.path.expanduser(credentials_file)
    if not os.path.exists(aws_credentials_file_path):
        return set()

    parser = configparser.ConfigParser()
    try:
        parser.read(aws_credentials_file_path)
    except configparser.MissingSectionHeaderError:
        return set()

    keys = set()
    for section in parser.sections():
        for var in (
            'aws_secret_access_key', 'aws_security_token',
            'aws_session_token',
        ):
            try:
                key = parser.get(section, var).strip()
                if key:
                    keys.add(key)
            except configparser.NoOptionError:
                pass
    return keys