23

When I launch an EC2 instance with an IAM role I can use boto3 on that EC2instance and not have to specify aws access and secret keys because boto3 reads them automatically.

>>> import boto3
>>> s3 = boto3.resource("s3")
>>> list(s3.buckets.all())[0]
s3.Bucket(name='my-bucket-name')

Question

I'm wondering if there is any way to get the access key and secret key from boto3? For example, how can I print them on to the standard console using print

Anthony
  • 33,838
  • 42
  • 169
  • 278

1 Answers1

49

There sure is (docs):

from boto3 import Session

session = Session()
credentials = session.get_credentials()
# Credentials are refreshable, so accessing your access key / secret key
# separately can lead to a race condition. Use this to get an actual matched
# set.
current_credentials = credentials.get_frozen_credentials()

# I would not recommend actually printing these. Generally unsafe.
print(current_credentials.access_key)
print(current_credentials.secret_key)
print(current_credentials.token)
Jordon Phillips
  • 14,963
  • 4
  • 35
  • 42
  • 4
    Good mention of 'get_frozen_credentials', method, which isn't mentioned in the already answered question referenced above. – simon Jun 27 '17 at 16:42
  • 1
    doubt: without passing credentials to 'Session` how does `boto3` know which credentials to return? or from which account the credentials it should return? – Kishor Pawar Jan 31 '18 at 09:39
  • 2
    To answer Kishor Pawar's question above, the call above to session would need to include the profile name in the config file. For example, I'm using: session = boto3.Session(profile_name='namexyz') where 'namexyz' is the section in my credentials file: [namexyz]. – RandomTask Aug 11 '18 at 16:49