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.
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.
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.
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.
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())
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With