How to use the awsume.awsumepy function in awsume

To help you get started, we’ve selected a few awsume examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github trek10inc / awsume / awsume / autoawsume / main.py View on Github external
def refresh_profile(auto_profile):
    logger.debug('Refreshing profile {}'.format(json.dumps(auto_profile, default=str)))
    try:
        session = awsumepy.awsume(*auto_profile.get('awsumepy_command').split(' '))
        return session
    except exceptions.AwsumeException as e:
        logger.debug('There was an issue refreshing the profile, not returning a session: {}'.format(e))
        logger.debug('', exc_info=True)
        return None
github trek10inc / awsume / awsume / autoawsume.py View on Github external
sourceCredentials = awsumepy.read_aws_cache(AWS_CACHE_DIRECTORY, autoProfile['awsume_cache_name'])
    stsClient = awsumepy.create_sts_client(sourceCredentials['AccessKeyId'],
                                           sourceCredentials['SecretAccessKey'],
                                           sourceCredentials['SessionToken'])
    try:
        response = stsClient.assume_role(RoleArn=autoProfile['aws_role_arn'], RoleSessionName=autoProfile['awsume_session_name'])
        session = response['Credentials']
        session['Expiration'] = session['Expiration'].astimezone(dateutil.tz.tzlocal())
        session['Expiration'] = session['Expiration'].strftime('%Y-%m-%d %H:%M:%S')
        session['region'] = sourceCredentials['region']

        autoProfile['aws_access_key_id'] = session['AccessKeyId']
        autoProfile['aws_secret_access_key'] = session['SecretAccessKey']
        autoProfile['aws_session_token'] = session['SessionToken']
        autoProfile['awsume_role_expiration'] = session['Expiration']
        awsumepy.write_auto_awsume_session(autoProfile['__name__'].replace('auto-refresh-', ''), autoProfile, AWS_CREDENTIALS_FILE)
    except botocore.exceptions.ClientError:
        pass
github trek10inc / awsume / awsume / autoawsume.py View on Github external
def refresh_session(autoProfile):
    """Refresh the `oldSession` role credentials.

    Parameters
    ----------
    - oldSession - the session to refresh;
    - roleArn - the role_arn used to make the assume_role call;
    - sessionName - what to name the assumed role session;

    Returns
    -------
    The refreshed role session
    """
    sourceCredentials = awsumepy.read_aws_cache(AWS_CACHE_DIRECTORY, autoProfile['awsume_cache_name'])
    stsClient = awsumepy.create_sts_client(sourceCredentials['AccessKeyId'],
                                           sourceCredentials['SecretAccessKey'],
                                           sourceCredentials['SessionToken'])
    try:
        response = stsClient.assume_role(RoleArn=autoProfile['aws_role_arn'], RoleSessionName=autoProfile['awsume_session_name'])
        session = response['Credentials']
        session['Expiration'] = session['Expiration'].astimezone(dateutil.tz.tzlocal())
        session['Expiration'] = session['Expiration'].strftime('%Y-%m-%d %H:%M:%S')
        session['region'] = sourceCredentials['region']

        autoProfile['aws_access_key_id'] = session['AccessKeyId']
        autoProfile['aws_secret_access_key'] = session['SecretAccessKey']
        autoProfile['aws_session_token'] = session['SessionToken']
        autoProfile['awsume_role_expiration'] = session['Expiration']
        awsumepy.write_auto_awsume_session(autoProfile['__name__'].replace('auto-refresh-', ''), autoProfile, AWS_CREDENTIALS_FILE)
    except botocore.exceptions.ClientError:
github trek10inc / awsume / examplePlugin / console.py View on Github external
def get_environment_credentials(self):
        """Get session credentials from the environment."""
        aws_region = 'us-east-1'
        if 'AWS_PROFILE' in os.environ:
            credentials_profiles = awsumepy.read_ini_file(awsumepy.AWS_CREDENTIALS_FILE)
            auto_profile = credentials_profiles[os.environ['AWS_PROFILE']]
            temp_credentials = {
                'sessionId': auto_profile['aws_access_key_id'],
                'sessionKey': auto_profile['aws_secret_access_key'],
                'sessionToken': auto_profile['aws_session_token']
            }
            if auto_profile.get('aws_region'):
                aws_region = auto_profile.get('aws_region')
        elif os.environ.get('AWS_ACCESS_KEY_ID') and os.environ.get('AWS_SECRET_ACCESS_KEY') and os.environ.get('AWS_SESSION_TOKEN'):
            temp_credentials = {
                'sessionId': os.environ['AWS_ACCESS_KEY_ID'],
                'sessionKey': os.environ['AWS_SECRET_ACCESS_KEY'],
                'sessionToken': os.environ['AWS_SESSION_TOKEN']
            }
            if os.environ.get('AWS_REGION'):
                aws_region = os.environ['AWS_REGION']
github trek10inc / awsume / awsume / autoawsume.py View on Github external
def refresh_expired_profiles(autoProfiles):
    """Refresh any expired autoProfiles.

    Parameters
    ----------
    - autoProfiles - the autoawsume profiles from the credentials profile
    """
    for profile in autoProfiles:
        userExpiration = datetime.datetime.strptime(autoProfiles[profile]['awsume_user_expiration'], '%Y-%m-%d %H:%M:%S')
        roleExpiration = datetime.datetime.strptime(autoProfiles[profile]['awsume_role_expiration'], '%Y-%m-%d %H:%M:%S')
        if roleExpiration < get_now():
            refresh_session(autoProfiles[profile])
        if userExpiration < get_now():
            awsumepy.remove_auto_profile(autoProfiles[profile]['__name__'].replace('auto-refresh-', ''))
github trek10inc / awsume / examplePlugin / console.py View on Github external
def post_awsume(self,
                    app,
                    args,
                    profiles,
                    user_session,
                    role_session):
        """Open the console using the currently AWSume'd credentials."""
        if args.open_console is True:
            if not role_session:
                awsumepy.safe_print('Cannot use these credentials to open the AWS Console.')
                return
            credentials, region = self.get_session_temp_credentials(role_session)
            response = self.make_aws_federation_request(credentials)
            signin_token = self.get_signin_token(response)
            console_url = self.get_console_url(signin_token, region)
            self.open_browser_to_url(console_url, args)
github trek10inc / awsume / awsume / autoawsume.py View on Github external
def main():
    while True:
        credentialsProfiles = awsumepy.read_ini_file(AWS_CREDENTIALS_FILE)
        autoRefreshProfiles = extract_auto_refresh_profiles(credentialsProfiles)
        refresh_expired_profiles(autoRefreshProfiles)
        earliestExpiration = get_earliest_expiration(autoRefreshProfiles)
        timeUntilEarliestExpiration = (earliestExpiration - get_now().replace(tzinfo=earliestExpiration.tzinfo)).total_seconds()
        if timeUntilEarliestExpiration <= 0:
            break
        # awsumepy.safe_print("autoawsume: Sleeping for " + str(timeUntilEarliestExpiration) + " seconds", file=sys.stderr)
        time.sleep(timeUntilEarliestExpiration)
    # awsumepy.safe_print("autoawsume: No more credentials left to refresh, shutting down", file=sys.stderr)