2015-11-07 55 views
10

我在法蘭克福地區的S3中使用aws lambda中的boto3到fecth對象。如何配置內嵌boto3的授權機制

v4是必要的。否則下面的錯誤將返回

"errorMessage": "An error occurred (InvalidRequest) when calling 
the GetObject operation: The authorization mechanism you have 
provided is not supported. Please use AWS4-HMAC-SHA256." 

實現方式來配置signature_version http://boto3.readthedocs.org/en/latest/guide/configuration.html

但自從我使用AWS的λ,我沒有獲得基本的配置特性

我AWS lambda函數的代碼

from __future__ import print_function 
import boto3 


def lambda_handler (event, context): 
    input_file_bucket = event["Records"][0]["s3"]["bucket"]["name"] 
    input_file_key = event["Records"][0]["s3"]["object"]["key"] 
    input_file_name = input_file_bucket+"/"+input_file_key 

    s3=boto3.resource("s3") 
    obj = s3.Object(bucket_name=input_file_bucket, key=input_file_key) 
    response = obj.get() 
    return event #echo first key valuesdf 

是否可以在此代碼中配置signature_version?例如使用Session。或者是否有任何解決方法?

回答

16

不使用默認的會話,請嘗試使用從boto3.session

import boto3 
import boto3.session 
session = boto3.session.Session(region_name='eu-central-1') 
s3client = session.client('s3', config= boto3.session.Config(signature_version='s3v4')) 
s3client.get_object(Bucket='<Bkt-Name>', Key='S3-Object-Key') 
+0

有沒有辦法從文件配置它?我在問,因爲我使用了一段代碼,其中'boto3'是依賴項,所以我沒有直接訪問來改變'client()'調用。 – bstempi

+0

您可以設置boto3.session.Session(profile_name ='profile1')其中profile1是使用AWS密鑰,令牌,所需區域和其他必要參數在.aws/credentials文件中定義的配置文件的名稱 – omuthu

+0

如果我不是使用AWS密鑰,我反而依靠EC2實例的元數據服務? – bstempi

4

我試過了會議的方式自定義會話和配置,但我有問題。這種方法更好地工作對我來說,你的里程可能會有所不同:

s3 = boto3.resource('s3', config=Config(signature_version='s3v4')) 

您需要,以使這項工作從botocore.client導入配置。請參閱下面的測試存儲桶的功能方法(列表對象)。這是假設你是從那裏您的認證管理的環境,如Amazon EC2或拉姆達與IAM角色運行它:

import boto3 
from botocore.client import Config 
from botocore.exceptions import ClientError 

def test_bucket(bucket): 
    print 'testing bucket: ' + bucket 
    try: 
     s3 = boto3.resource('s3', config=Config(signature_version='s3v4')) 
     b = s3.Bucket(bucket) 
     objects = b.objects.all() 

     for obj in objects: 
      print obj.key 
     print 'bucket test SUCCESS' 
    except ClientError as e: 
     print 'Client Error' 
     print e 
     print 'bucket test FAIL' 

爲了測試它,只需撥打一個桶名稱的方式。你的角色必須授予適當的權限。