问题
I have a program that sometimes needs to make requests to the AWS API using boto3. Sometimes somebody runs this without providing any credentials, and when the script gets to point where it needs to interact with AWS it crashes with a botocore.exceptions.NoCredentialsError
.
I'd like to preempt this by validating when the script starts whether any credentials have been provided and quitting with an explanatory message if they have not. However, as noted in the docs, there are loads of possible ways to provide credentials that boto3 will understand, and I want to let my user use any of them (rather than e.g. requiring that they provide credentials as environment variables).
How can I quickly check whether credentials are available at the start of my script (without making an unneeded request to the AWS API)?
回答1:
Although the docs don't explicitly say so, the Session.get_credentials method will return a botocore.credentials.Credentials
object if credentials are available or None
otherwise.
So the check I need looks something like this:
import sys
import boto3
if boto3.session.Session().get_credentials() is None:
print('Please provide Boto3 credentials, e.g. via the AWS_ACCESS_KEY_ID '
'and AWS_SECRET_ACCESS_KEY environment variables.')
sys.exit(-1)
来源:https://stackoverflow.com/questions/49361965/check-whether-aws-credentials-are-present-without-making-any-requests