Read credentials from EC2 instance metadata (IAM role)

    :return:
348628
def read_creds_from_ec2_instance_metadata():
    
    creds = init_creds()
    try:
        has_role = requests.get('http://169.254.169.254/latest/meta-data/iam/security-credentials', timeout = 1)
        if has_role.status_code == 200:
            iam_role = has_role.text
            credentials = requests.get('http://169.254.169.254/latest/meta-data/iam/security-credentials/%s/' %
                                       iam_role.strip()).json()
            for c in ['AccessKeyId', 'SecretAccessKey']:
                creds[c] = credentials[c]
            creds['SessionToken'] = credentials['Token']
        return creds
    except Exception as e:
        return False
76719
def print_ec2_info(region,
                   instance_id,
                   access_key_id,
                   secret_access_key,
                   username):
    
    data = get_ec2_info(instance_id=instance_id,
                        region=region,
                        access_key_id=access_key_id,
                        secret_access_key=secret_access_key,
                        username=username)

    log_green("region: %s" % data['region'])
    log_green("Instance_type: %s" % data['instance_type'])
    log_green("Instance state: %s" % data['state'])
    log_green("Public dns: %s" % data['public_dns_name'])
    log_green("Ip address: %s" % data['ip_address'])
    log_green("volume: %s" % data['volume'])
    log_green("user: %s" % data['username'])
    log_green("ssh -i %s %s@%s" % (env.key_filename,
                                   username,
                                   data['ip_address']))
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
831231
public static Map<String, IAMSecurityCredential> getIAMSecurityCredentials() {
        Map<String, IAMSecurityCredential> credentialsInfoMap = new HashMap<String, IAMSecurityCredential>();

        List<String> credentials = getItems(EC2_METADATA_ROOT
                + "/iam/security-credentials");

        if (null != credentials) {
            for (String credential : credentials) {
                String json = getData(EC2_METADATA_ROOT
                        + "/iam/security-credentials/" + credential);
                try {
                    IAMSecurityCredential credentialInfo = mapper
                            .readValue(json, IAMSecurityCredential.class);
                    credentialsInfoMap.put(credential, credentialInfo);
                } catch (Exception e) {
                    log.warn("Unable to process the credential (" + credential
                            + "). " + e.getMessage(), e);
                }
            }
        }
        return credentialsInfoMap;
    }
973231
def _get_role_arn(name, **conn_params):
    '''
    
    '''
    if name.startswith('arn:aws:iam'):
        return name
    role = __salt__['boto_iam.describe_role'](name, **conn_params)
    rolearn = role.get('arn') if role else None

    return rolearn
256019
function getEC2IAMRole(callback) {
		httpRequest({host: EC2_METADATA_HOST, path: SECURITY_CREDENTIALS_RESOURCE}, null, function(error, role, httpResponse) {
			callback(error, _.isString(role) ? role.trim() : role, httpResponse);
		});
	}
1232262
def instance_admin_api(self):
        """"""
        if self._instance_admin_api is None:
            self._instance_admin_api = InstanceAdminClient(
                credentials=self.credentials, client_info=_CLIENT_INFO
            )
        return self._instance_admin_api
904761
def _get_credentials():
    '''
    
    '''
    ret = {
        'user': False,
        'passwd': False
    }

    # Loop through opts, grains, and pillar
    # Return the first acceptable configuration found
    for item in ret:
        for struct in [__opts__, __grains__, __pillar__]:
            # Look for the config key
            # Support old-style config format and new
            for config_key in __valid_configs[item]:
                value = salt.utils.data.traverse_dict_and_list(
                    struct,
                    config_key,
                    None)
                if value:
                    ret[item] = value
                    break
    return ret['user'], ret['passwd']
440067
def _get_explicit_environ_credentials():
    """"""
    explicit_file = os.environ.get(environment_vars.CREDENTIALS)

    if explicit_file is not None:
        credentials, project_id = _load_credentials_from_file(
            os.environ[environment_vars.CREDENTIALS])

        return credentials, project_id

    else:
        return None, None
48959
def _generate_iam_invoke_role(self):
        

        invoke_assume = {
            "Version": "2012-10-17",
            "Statement": [
                {
                    "Action": "sts:AssumeRole",
                    "Principal": {
                        "Service": "apigateway.amazonaws.com"
                    },
                    "Effect": "Allow",
                    "Sid": ""
                }
            ]
        }
        self.tf_conf['resource']['aws_iam_role']['invoke_role'] = {
            'name': self.resource_name + '-invoke',
            'assume_role_policy': json.dumps(invoke_assume),
        }
        self.tf_conf['output']['iam_invoke_role_arn'] = {
            'value': '${aws_iam_role.invoke_role.arn}'
        }
        self.tf_conf['output']['iam_invoke_role_unique_id'] = {
            'value': '${aws_iam_role.invoke_role.unique_id}'
        }
310130
def readMyEC2Tag(tagName, connection=None):
  
  assert isinstance(tagName, basestring), ("tagName must be a string but is %r" % tagName)

  # Load metadata. if == {} we are on localhost
  # http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/AESDG-chapter-instancedata.html

  if not connection:
    # Assume AWS credentials are in the environment or the instance is using an IAM role
    connection = boto.ec2.connect_to_region(myRegion())

  return readInstanceTag(connection=connection,
                         instanceID=myInstanceID(),
                         tagName=tagName)
156074
def _readClusterSettings(self):
        
        instanceMetaData = get_instance_metadata()
        region = zoneToRegion(self._zone)
        conn = boto.ec2.connect_to_region(region)
        instance = conn.get_all_instances(instance_ids=[instanceMetaData["instance-id"]])[0].instances[0]
        self.clusterName = str(instance.tags["Name"])
        self._buildContext()
        self._subnetID = instance.subnet_id
        self._leaderPrivateIP = instanceMetaData['local-ipv4']  # this is PRIVATE IP
        self._keyName = list(instanceMetaData['public-keys'].keys())[0]
        self._tags = self.getLeader().tags
        self._masterPublicKey = self._setSSH()
984483
def _generate_iam_role(self):
        
        pol = {
            "Version": "2012-10-17",
            "Statement": [
                {
                    "Action": "sts:AssumeRole",
                    "Principal": {
                        "Service": "lambda.amazonaws.com"
                    },
                    "Effect": "Allow",
                    "Sid": ""
                }
            ]
        }

        self.tf_conf['resource']['aws_iam_role'] = {}
        self.tf_conf['resource']['aws_iam_role']['lambda_role'] = {
            'name': self.resource_name,
            'assume_role_policy': json.dumps(pol),
        }
        self.tf_conf['output']['iam_role_arn'] = {
            'value': '${aws_iam_role.lambda_role.arn}'
        }
        self.tf_conf['output']['iam_role_unique_id'] = {
            'value': '${aws_iam_role.lambda_role.unique_id}'
        }
924858
def assume_role_credentials(self, arn):
        """"""
        log.info("Assuming role as %s", arn)

        # Clear out empty values
        for name in ['AWS_ACCESS_KEY_ID', 'AWS_SECRET_ACCESS_KEY', 'AWS_SECURITY_TOKEN', 'AWS_SESSION_TOKEN']:
            if name in os.environ and not os.environ[name]:
                del os.environ[name]

        sts = self.amazon.session.client("sts")
        with self.catch_boto_400("Couldn't assume role", arn=arn):
            creds = sts.assume_role(RoleArn=arn, RoleSessionName="aws_syncr")

        return {
              'AWS_ACCESS_KEY_ID': creds["Credentials"]["AccessKeyId"]
            , 'AWS_SECRET_ACCESS_KEY': creds["Credentials"]["SecretAccessKey"]
            , 'AWS_SECURITY_TOKEN': creds["Credentials"]["SessionToken"]
            , 'AWS_SESSION_TOKEN': creds["Credentials"]["SessionToken"]
            }
1322953
def get_role_arn(role_name, env, region):
    
    session = boto3.Session(profile_name=env, region_name=region)
    iam_client = session.client('iam')

    LOG.debug('Searching for %s.', role_name)

    role = iam_client.get_role(RoleName=role_name)
    role_arn = role['Role']['Arn']

    LOG.debug("Found role's %s ARN %s", role_name, role_arn)

    return role_arn
793834
def get_nas_credentials(self, identifier, **kwargs):
        
        result = self.network_storage.getObject(id=identifier, **kwargs)
        return result
95713
def get_dockercfg_credentials(self, docker_registry):
        
        if not self.registry_secret_path:
            return {}

        dockercfg = Dockercfg(self.registry_secret_path)
        registry_creds = dockercfg.get_credentials(docker_registry)
        if 'username' not in registry_creds:
            return {}

        return {
            'basic_auth_username': registry_creds['username'],
            'basic_auth_password': registry_creds['password'],
        }