私は、期限切れになっている可能性のあるAWSキーをいくつか使用するPythonコードを書こうとしています。文字列としてAWSキーペアが与えられ、boto3を使用してそのキーペアが有効かどうかを確認する必要があります。os.systemを使用して実行するようなことはしたくないのですが、
echo "$aws_key_id
$aws_secret_key\n\n" | aws configure
そして、aws list-buckets.
答えは次のようになるはずです
def check_aws_validity(key_id, secret):
pass
ここでkey_id
、 とsecret
は文字列です。
これは、boto3 を使用して GET または PUT なしで S3 資格情報を検証するboto3.profile にキーがないため。
前もって感謝します!
編集John Rotenstein の回答から、次の関数が動作するようになりました。
def check_aws_validity(key_id, secret):
try:
client = boto3.client('s3', aws_access_key_id=key_id, aws_secret_access_key=secret)
response = client.list_buckets()
return true
except Exception as e:
if str(e)!="An error occurred (InvalidAccessKeyId) when calling the ListBuckets operation: The AWS Access Key Id you provided does not exist in our records.":
return true
return false
ベストアンサー1
そのような資格証明を検証する方法は存在します。それはSTS の GetCallerIdentityAPI呼び出し(boto3 メソッド ドキュメント)。
有効期限が切れた一時認証情報の場合:
>>> import boto3
>>> sts = boto3.client('sts')
>>> sts.get_caller_identity()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/home/jantman/venv/lib/python3.8/site-packages/botocore/client.py", line 276, in _api_call
return self._make_api_call(operation_name, kwargs)
File "/home/jantman/venv/lib/python3.8/site-packages/botocore/client.py", line 586, in _make_api_call
raise error_class(parsed_response, operation_name)
botocore.exceptions.ClientError: An error occurred (ExpiredToken) when calling the GetCallerIdentity operation: The security token included in the request is expired
資格情報が無効の場合:
>>> import boto3
>>> sts = boto3.client('sts')
>>> sts.get_caller_identity()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/home/jantman/venvs/current/lib/python3.8/site-packages/botocore/client.py", line 316, in _api_call
return self._make_api_call(operation_name, kwargs)
File "/home/jantman/venvs/current/lib/python3.8/site-packages/botocore/client.py", line 626, in _make_api_call
raise error_class(parsed_response, operation_name)
botocore.exceptions.ClientError: An error occurred (InvalidClientTokenId) when calling the GetCallerIdentity operation: The security token included in the request is invalid
有効な資格情報(ID が X に置き換えられます):
>>> import boto3
>>> sts = boto3.client('sts')
>>> sts.get_caller_identity()
{'UserId': 'AROAXXXXXXXXXXXXX:XXXXXXX', 'Account': 'XXXXXXXXXXXX', 'Arn': 'arn:aws:sts::XXXXXXXXXXXX:assumed-role/Admin/JANTMAN', 'ResponseMetadata': {'RequestId': 'f44ec1d9-XXXX-XXXX-XXXX-a26c85be1c60', 'HTTPStatusCode': 200, 'HTTPHeaders': {'x-amzn-requestid': 'f44ec1d9-XXXX-XXXX-XXXX-a26c85be1c60', 'content-type': 'text/xml', 'content-length': '426', 'date': 'Thu, 28 May 2020 10:45:36 GMT'}, 'RetryAttempts': 0}}
無効な資格情報では例外が発生し、有効な資格情報では例外が発生しないため、次のような操作を行うことができます。
import boto3
sts = boto3.client('sts')
try:
sts.get_caller_identity()
print("Credentials are valid.")
except boto3.exceptions.ClientError:
print("Credentials are NOT valid.")