检查是否存在AWS凭证而不发出任何请求 [英] Check whether AWS credentials are present without making any requests

查看:48
本文介绍了检查是否存在AWS凭证而不发出任何请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个程序,有时需要使用boto3向AWS API发出请求.有时有人在不提供任何凭证的情况下运行此脚本,当脚本指出需要与AWS进行交互的位置时,它会因 botocore.exceptions.NoCredentialsError 崩溃.

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.

我想通过验证脚本是否在启动时验证是否提供了任何凭据,如果没有提供凭据,请退出并附带一条解释性消息,以抢占先机.但是,正如文档中提到的 所示,加载提供boto3可以理解的凭据的可能方法,我想让我的用户使用其中的任何一种(而不是例如要求它们提供凭据作为环境变量).

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).

如何在脚本开始时快速检查凭证是否可用(无需对AWS API进行不必要的请求)?

How can I quickly check whether credentials are available at the start of my script (without making an unneeded request to the AWS API)?

推荐答案

尽管文档中没有明确说明,但

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)

这篇关于检查是否存在AWS凭证而不发出任何请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆