簡體   English   中英

如何配置與boto3內聯的授權機制

[英]How to configure authorization mechanism inline with boto3

我在 aws lambda 中使用 boto3 到位於法蘭克福地區的 S3 中的 fecth object。

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 lambda,所以我無權訪問底層配置文件

我的AWS的代碼 lambda function

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 為例。 或者有什么解決方法嗎?

而不是使用默認會話,嘗試使用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')

我嘗試了會話方法,但我遇到了問題。 這種方法對我來說效果更好,你的里程可能有所不同:

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

您需要從botocore.client導入Config才能使其正常工作。 請參閱下文,了解測試存儲桶的功能方法(列表對象)。 這假設您從管理身份驗證的環境運行它,例如Amazon EC2或具有IAM角色的Lambda:

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'

要測試它,只需使用存儲桶名稱調用該方法。 您的角色必須授予適當的權限。

使用對我有用的資源。

from botocore.client import Config
import boto3
s3 = boto3.resource("s3", config=Config(signature_version="s3v4"))
return s3.meta.client.generate_presigned_url(
    "get_object", Params={"Bucket": AIRFLOW_BUCKET, "Key": key}, ExpiresIn=expTime
)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM