Skip to content

Instantly share code, notes, and snippets.

@diogoaurelio
Created December 1, 2017 11:11
Show Gist options
  • Save diogoaurelio/ea4c2df69a00f3fe9c7290eadfdbd3a8 to your computer and use it in GitHub Desktop.
Save diogoaurelio/ea4c2df69a00f3fe9c7290eadfdbd3a8 to your computer and use it in GitHub Desktop.
aws_instance_temp_credentials.py
def get_temp_credentials(role=DEFAULT_INSTANCE_ROLE):
""" Retrieves temp AWS credentials """
query_uri = 'http://169.254.169.254/latest/meta-data/iam/security-credentials/{}'.format(role)
print('Querying AWS for credentials - {}'.format(query_uri))
try:
sts_credentials = requests.get(query_uri).json()
if isinstance(sts_credentials, dict) and \
sts_credentials.get('Code') == 'Success':
print('Successfully retrieved temp AWS credentials.')
return sts_credentials
print('There was a problem when retrieving temp credentials '
'from AWS. Here\'s the response: \n{}'.format(sts_credentials))
except (HTTPError, ConnectionError, Timeout) as err:
msg = 'Unable to query AWS for credentials: {}'.format(err)
print(msg)
except ValueError as err:
msg = 'Error: unable to decode json from \'None\' value - {} ' \
'(hint: most likely the role you are using is wrong)'.format(err)
print(msg)
except Exception as err:
msg = 'Failed to get AWS role temp credentials: {}'.format(err)
print(msg)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment