Skip to content

Commit

Permalink
Autoawsume fixes
Browse files Browse the repository at this point in the history
  • Loading branch information
mbarneyjr committed Sep 29, 2019
1 parent f176c14 commit 3ed8fad
Show file tree
Hide file tree
Showing 6 changed files with 38 additions and 21 deletions.
2 changes: 1 addition & 1 deletion awsume/__data__.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
version = '4.1.5a6'
version = '4.1.5a7'

name = 'awsume'
author = 'Trek10, Inc'
Expand Down
27 changes: 17 additions & 10 deletions awsume/autoawsume/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
from datetime import datetime, timedelta

from ..awsumepy.lib.aws_files import get_aws_files, delete_section
from .. import awsumepy


def main():
Expand All @@ -15,22 +16,28 @@ def main():
auto_profiles = {k: dict(v) for k, v in credentials._sections.items() if k.startswith('autoawsume-')}

expirations = []
for _, auto_profile in auto_profiles.items():
for profile_name, auto_profile in auto_profiles.items():
expiration = datetime.strptime(auto_profile['expiration'], '%Y-%m-%d %H:%M:%S')
source_expiration = datetime.strptime(auto_profile['source_expiration'], '%Y-%m-%d %H:%M:%S')

if source_expiration < datetime.now() + timedelta(minutes=5):
continue

if expiration < datetime.now() + timedelta(minutes=5):
subprocess.run(auto_profile.get('awsumepy_command').split(' '), stdout=subprocess.PIPE, stderr=subprocess.PIPE)
expirations.append(datetime.now() + timedelta(hours=1))
# + timedelta(minutes=5)
# awsumepy.awsume(*auto_profile.get('awsumepy_command').split(' '))
# expirations.append(datetime.now() + timedelta(hours=1))
if source_expiration < datetime.now():
if expiration < datetime.now():
delete_section(profile_name, credentials_file)
else:
expirations.append(expiration)
else:
expirations.append(expiration)
if expiration < datetime.now():
session = awsumepy.awsume(*auto_profile.get('awsumepy_command').split(' '))
expirations.append(session.awsume_credentials.get('Expiration'))
else:
expirations.append(expiration)
expirations.append(source_expiration)

if not expirations:
break

earliest_expiration = min(expirations)
time_to_sleep = (earliest_expiration - datetime.now().replace(tzinfo=earliest_expiration.tzinfo)).total_seconds()
time_to_sleep = (earliest_expiration - datetime.now().replace(tzinfo=earliest_expiration.tzinfo)).total_seconds() + 60
time.sleep(time_to_sleep)
4 changes: 3 additions & 1 deletion awsume/awsumepy/app.py
Original file line number Diff line number Diff line change
Expand Up @@ -230,12 +230,14 @@ def export_data(self, credentials: dict, awsume_flag: str, awsume_list: list):
if self.is_interactive:
print(awsume_flag, end=' ')
print(' '.join(awsume_list))
return boto3.Session(
session = boto3.Session(
aws_access_key_id=credentials.get('AccessKeyId'),
aws_secret_access_key=credentials.get('SecretAccessKey'),
aws_session_token=credentials.get('SessionToken'),
region_name=credentials.get('Region'),
)
session.awsume_credentials = credentials
return session


def run(self, system_arguments: list):
Expand Down
8 changes: 7 additions & 1 deletion awsume/awsumepy/default_plugins.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import argparse
import configparser
import json
import os
import colorama


Expand Down Expand Up @@ -266,7 +267,7 @@ def collect_aws_profiles(config: dict, arguments: argparse.Namespace, credential
if short_name not in profiles:
profiles[short_name] = {}
profiles[short_name].update(profile)
logger.debug('Colelcted {} profiles'.format(len(profiles)))
logger.debug('Collected {} profiles'.format(len(profiles)))
return profiles


Expand Down Expand Up @@ -382,6 +383,11 @@ def get_assume_role_credentials_mfa_required(config: dict, arguments: argparse.N
elif target_profile.get('credential_source') == 'Environment':
logger.debug('Using current environment to assume role')
source_session = {}

if arguments.auto_refresh and os.environ.get('AWS_PROFILE').startswith('autoawsume-'):
os.environ.pop('AWS_PROFILE')
os.environ.pop('AWS_DEFAULT_PROFILE')

role_session = aws_lib.assume_role(
source_session,
target_profile.get('role_arn'),
Expand Down
17 changes: 9 additions & 8 deletions awsume/awsumepy/lib/aws.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,15 +29,14 @@ def assume_role(

logger.debug('Assuming role: {}'.format(role_arn))
logger.debug('Session name: {}'.format(session_name))
boto_session = boto3.session.Session(
aws_access_key_id=source_credentials.get('AccessKeyId'),
aws_secret_access_key=source_credentials.get('SecretAccessKey'),
aws_session_token=source_credentials.get('SessionToken'),
region_name=region,
)
role_sts_client = boto_session.client('sts') # type: botostubs.STS

try:
boto_session = boto3.session.Session(
aws_access_key_id=source_credentials.get('AccessKeyId'),
aws_secret_access_key=source_credentials.get('SecretAccessKey'),
aws_session_token=source_credentials.get('SessionToken'),
region_name=region,
)
role_sts_client = boto_session.client('sts') # type: botostubs.STS
kwargs = { 'RoleSessionName': session_name, 'RoleArn': role_arn }
if external_id:
kwargs['ExternalId'] = external_id
Expand All @@ -46,7 +45,9 @@ def assume_role(
if mfa_serial:
kwargs['SerialNumber'] = mfa_serial
kwargs['TokenCode'] = mfa_token or profile_lib.get_mfa_token()
logger.debug('Assuming role now')
role_session = role_sts_client.assume_role(**kwargs).get('Credentials')
logger.debug('Received role credentials')
role_session['Expiration'] = role_session['Expiration'].astimezone(dateutil.tz.tzlocal())
role_session['Region'] = region or boto_session.region_name
except Exception as e:
Expand Down
1 change: 1 addition & 0 deletions docs/changelog.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
- `--role-arn <partition>:<account_id>:<role_name>`
- `--principal-arn <partition>:<account_id>:<provider_na,e>`
- Logs expiration for inline role assumption
- Fixed autoawsume bug with profile name and expired (removed) autoawsume profile

## [4.1.4] - 2019-09-23 - Bug Fix

Expand Down

0 comments on commit 3ed8fad

Please sign in to comment.