2015-10-20 66 views
6

我有一個非常簡單的腳本從一個桶下載文件。該文件正在利用KMS加密密鑰,我的策略和角色設置正確,但仍然出現錯誤。你如何在AWS KMS中使用Boto3 download_file?

代碼

#!/usr/bin/env python 
import boto3 
s3_client = boto3.client('s3') 
s3_client.download_file('testtesttest', 'test.txt', '/tmp/test.txt') 

錯誤

Traceback (most recent call last): 
    File "./getfile.py", line 4, in <module> 
s3_client.download_file('testtesttest', 'test.txt', '/tmp/test.txt') 
File "/usr/local/lib/python2.7/dist-packages/boto3/s3/inject.py", line 91, in download_file 
extra_args=ExtraArgs, callback=Callback) 
File "/usr/local/lib/python2.7/dist-packages/boto3/s3/transfer.py", line 659, in download_file 
extra_args, callback) 
File "/usr/local/lib/python2.7/dist-packages/boto3/s3/transfer.py", line 674, in _download_file 
self._get_object(bucket, key, filename, extra_args, callback) 
File "/usr/local/lib/python2.7/dist-packages/boto3/s3/transfer.py", line 698, in _get_object 
extra_args, callback) 
File "/usr/local/lib/python2.7/dist-packages/boto3/s3/transfer.py", line 712, in _do_get_object 
**extra_args) 
File "/usr/local/lib/python2.7/dist-packages/botocore/client.py", line 301, in _api_call 
return self._make_api_call(operation_name, kwargs) 
File "/usr/local/lib/python2.7/dist-packages/botocore/client.py", line 386, in _make_api_call 
raise ClientError(parsed_response, operation_name) 
botocore.exceptions.ClientError: An error occurred (InvalidArgument) when calling the GetObject operation: Requests specifying Server Side Encryption with AWS KMS managed keys require AWS Signature Version 4. 
+0

給未來讀者的提示:'s3v4'是默認的,所以你不需要明確地指定它,除非它從某個配置文件或環境中選擇了它。檢入'boto3.client('s3')。meta.config.signature_version'。 – wim

回答

12

想通了

代碼

#!/usr/bin/env python 
import boto3 
from botocore.client import Config 
s3_client = boto3.client('s3', config=Config(signature_version='s3v4')) 
s3_client.download_file('testtesttest', 'test.txt', '/tmp/test.txt') 
+0

謝謝!我一直試圖弄清楚這一個小時的好一段時間。你讓我的一天更容易。 – Valdogg21

+0

沒問題,很高興我能幫上忙! @ Valdogg21 – Laurence

+0

Pl接受你的答案,如果它解決了這個問題:) – Dawny33

4

您可能還想知道如何使用kms密鑰將文件上傳到s3。

s3_client = boto3.client('s3', config=Config(signature_version='s3v4')) 
s3_client.upload_file(filename, bucketname, objectkey, ExtraArgs={"ServerSideEncryption": "aws:kms", "SSEKMSKeyId": <somekmskeyid>}) 

如果您不提供kms密鑰id - 那麼默認情況下它使用s3 kms主密鑰。