Search code examples
pythonboto3boto

Best way to read aws credentials file


In my python code I need to extract AWS credentials AWS_SECRET_ACCESS_KEY and AWS_ACCESS_KEY_ID which are stored in the plain text file as described here: https://docs.aws.amazon.com/sdkref/latest/guide/file-format.html

I know the name of the file: AWS_SHARED_CREDENTIALS_FILE and the name of profile: AWS_PROFILE.

My current approach is to read and parse this file in python by myself to get AWS_SECRET_ACCESS_KEY and AWS_ACCESS_KEY_ID.

But I hope there is already standard way to get it using boto3 or some other library. Please suggest.


Solution

  • Would something like this work for you, or am I misunderstanding the question? Basically start a session for the appropriate profile (or the default, I guess), and then query those values from the credentials object:

        session = boto3.Session(profile_name=<...your-profile...>)
        credentials = session.get_credentials()
        print("AWS_ACCESS_KEY_ID = {}".format(credentials.access_key))
        print("AWS_SECRET_ACCESS_KEY = {}".format(credentials.secret_key))
        print("AWS_SESSION_TOKEN = {}".format(credentials.token))