boto3 equivalent of Powershell's Set-AWSCredential

As the title implies, I’m curious if there is a way to save credentials in the default credentials file.

In Powershell it’s straightforward (below), but I haven’t come across this type of functionality in Python/boto3.

PS C:> Set-AWSCredential -AccessKey AKIAIOSFODNN7EXAMPLE -SecretKey wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY -StoreAs MyProfileName


Related discussions:

Perhaps this is what you’re looking for?

The mechanism in which boto3 looks for credentials is to search through a list of possible locations and stop as soon as it finds credentials. The order in which Boto3 searches for credentials is…

I don’t believe boto3 provides a way to store your credentials like this. You’d want to use

aws configure

You can use .aws/credential and call it in python

Look at the documentation for the ‘configure’ command. You can store multiple profiles in your aws credentials file ( though you have to edit the file to do so ), but the recommended approach is to store the key and secret in ephemeral environment variables so they can’t be scraped from the file.

You don’t need boto3 specifically to do this. The following Python code does what you want:

import configparser

configParser = configparser.RawConfigParser()
configParser.read(home_dir+‘/.aws/config’)

configParser.add_section(‘profile myprofile’)
configParser.set(‘profile myprofile’, ‘aws_access_key_id’, accessKey)
configParser.set(‘profile myprofile’, ‘aws_secret_access_key’, secretAccessKey)
configParser.set(‘profile myprofile’, ‘region’, region)

with open(home_dir+‘/.aws/config’, ‘wb’) as aws_config_wfh:
configParser.write(aws_config_wfh)