Skip to content

Instantly share code, notes, and snippets.

@wjimenez5271
Created January 13, 2016 22:54
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save wjimenez5271/defeede8eb4a63afc9d8 to your computer and use it in GitHub Desktop.
Save wjimenez5271/defeede8eb4a63afc9d8 to your computer and use it in GitHub Desktop.
Simple python 2.7 implementation of a config reader for ~/.aws/credentials file
def get_profile_credentials(profile_name):
from ConfigParser import ConfigParser
from ConfigParser import ParsingError
from ConfigParser import NoOptionError
from ConfigParser import NoSectionError
from os import path
config = ConfigParser()
config.read([path.join(path.expanduser("~"),'.aws/credentials')])
try:
aws_access_key_id = config.get(profile_name, 'aws_access_key_id')
aws_secret_access_key = config.get(profile_name, 'aws_secret_access_key')
except ParsingError:
print('Error parsing config file')
raise
except (NoSectionError, NoOptionError):
try:
aws_access_key_id = config.get('default', 'aws_access_key_id')
aws_secret_access_key = config.get('default', 'aws_secret_access_key')
except (NoSectionError, NoOptionError):
print('Unable to find valid AWS credentials')
raise
return aws_access_key_id, aws_secret_access_key
@ggworld
Copy link

ggworld commented Oct 7, 2019

in Python 3:
def get_profile_credentials(profile_name):
from configparser import ConfigParser
from configparser import ParsingError
from configparser import NoOptionError
from configparser import NoSectionError
from os import path
config = ConfigParser()
config.read([path.join(path.expanduser("~"),'.aws/credentials')])
try:
aws_access_key_id = config.get(profile_name, 'aws_access_key_id')
aws_secret_access_key = config.get(profile_name, 'aws_secret_access_key')
except ParsingError:
print('Error parsing config file')
raise
except (NoSectionError, NoOptionError):
try:
aws_access_key_id = config.get('default', 'aws_access_key_id')
aws_secret_access_key = config.get('default', 'aws_secret_access_key')
except (NoSectionError, NoOptionError):
print('Unable to find valid AWS credentials')
raise
return aws_access_key_id, aws_secret_access_key

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment