14

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.

April Polubiec
  • 598
  • 5
  • 13
  • 3
    Are you trying to do this so that you can eventually make API calls to AWS in your Python script? If so, just use Boto3 and it will automatically read the config file. – Mark B Nov 26 '19 at 13:33

1 Answers1

21

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.

snakecharmerb
  • 47,570
  • 11
  • 100
  • 153
  • 1
    You don't need `os.path.join()`. OP can just do `os.path.expanduser('~/.aws/credentials')` – Flair Oct 15 '20 at 23:24
  • 1
    `Path('~/.aws/credentials').expanduser()` worked for me, not sure if it is a newer version of pathlib/python thing – erncyp Nov 09 '20 at 17:12