Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Boto3: get credentials dynamically?

I am struggling to find out how I can get my aws_access_key_id and aws_secret_access_key dynamically from my code.

In boto2 I could do the following: boto.config.get_value('Credentials', 'aws_secret_access_key') but I can't seem to find a similar method in boto3. I was able to find the keys if I look in boto3.Session()._session._credentials but that seems like the mother of all hacks to me and I would rather not go down that road.

like image 708
Mo. Avatar asked Mar 29 '16 14:03

Mo.


Video Answer


3 Answers

It's generally a best practice to only use temporary credentials. You can get temporary credentials with STS.get_session_token.

EDIT: As of this PR, you can access the current session credentials like so:

import boto3  session = boto3.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. credentials = credentials.get_frozen_credentials() access_key = credentials.access_key secret_key = credentials.secret_key  redshift = session.client('redshift') ... 

I would still recommend using temporary credentials scoped to exactly what redshift needs.

like image 164
Jordon Phillips Avatar answered Sep 18 '22 20:09

Jordon Phillips


Use botocore

>>> import botocore.session
>>> session = botocore.session.get_session()

>>> session.get_credentials().access_key
'AKIAABCDEF6RWSGI234Q'

>>> session.get_credentials().secret_key
'abcdefghijkl+123456789+qbcd'

>>> session.get_config_variable('region')
'us-east-1'
like image 38
helloV Avatar answered Sep 18 '22 20:09

helloV


Can I suggest that accessing the keys is WRONG using boto3:

import boto3
session = boto3.Session(profile_name="my-profile")

dynamodb = session.resource(
    "dynamodb",
    region_name=session.region_name,
    # aws_access_key_id=session.get_credentials().access_key,
    # aws_secret_access_key=session.get_credentials().secret_key,
)

Notice, I commented out accessing the keys because 1:

Any clients created from this session will use credentials from the [my-profile] section of ~/.aws/credentials.

like image 45
jakebrinkmann Avatar answered Sep 19 '22 20:09

jakebrinkmann