Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Having trouble reading AWS config file with python configparser

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.

like image 529
April Polubiec Avatar asked Nov 26 '19 13:11

April Polubiec


People also ask

How do I use config files in Python?

Python Configuration File The simplest way to write configuration files is to simply write a separate file that contains Python code. You might want to call it something like databaseconfig.py . Then you could add the line *config.py to your . gitignore file to avoid uploading it accidentally.

What does Configparser do in Python?

This module provides the ConfigParser class which implements a basic configuration language which provides a structure similar to what's found in Microsoft Windows INI files. You can use this to write Python programs which can be customized by end users easily.

How do I read an INI file in Python?

To read and write INI files, we can use the configparser module. This module is a part of Python's standard library and is built for managing INI files found in Microsoft Windows. This module has a class ConfigParser containing all the utilities to play around with INI files. We can use this module for our use case.


1 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.expanduser

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

or use pathlib.Path.expanduser

path = pathlib.PosixPath('~/.aws/credentials')
config.read(path.expanduser())
like image 123
snakecharmerb Avatar answered Oct 21 '22 17:10

snakecharmerb