Having trouble reading AWS config file with python configparser

Question:

I ran aws configure to set my access key ID and secret access key. Those are now stored in ~/.aws/credentials which looks like:

[default]
aws_access_key_id = ######
aws_secret_access_key = #######

I’m trying to access those keys for a script I’m writing using configparser. This is my code:

import configparser

def main():
    ACCESS_KEY_ID = ''
    ACCESS_SECRET_KEY = ''

    config = configparser.RawConfigParser()

    print (config.read('~/.aws/credentials')) ## []
    print (config.sections())                 ## []
    ACCESS_KEY_ID = config.get('default', 'aws_access_key_id') ##configparser.NoSectionError: No section: 'default'
    print(ACCESS_KEY_ID)

if __name__ == '__main__':
    main()

I run the script using python3 script.py. Any ideas of what’s going on here? Seems like configparser just isn’t reading/finding the file at all.

Asked By: April Polubiec

||

Answers:

configparser.read doesn’t try to expand the leading tilde ‘~’ in the path to your home directory.

You can provide a relative or absolute path

config.read('/home/me/.aws/credentials')

or use os.path.expanduser1

path = os.path.expanduser('~/aws/credentials')
config.read(path)

or use pathlib.Path.expanduser

path = pathlib.PosixPath('~/.aws/credentials')
config.read(path.expanduser())

1 Improved code from Flair‘s comment.

Answered By: snakecharmerb