如何为 boto3.s3.transfer.TransferConfig 添加加密以进行 s3 文件上传



我正在尝试使用 boto3 file_upload方法将文件上传到 s3。在需要服务器端加密之前,这非常简单。过去,我曾使用put_object来实现这一点。

这样:

import boto3
s3 = boto3.resource('s3')
s3.Bucket(bucket).put_object(Key=object_name,
                             Body=data,
                             ServerSideEncryption='aws:kms',
                             SSEKMSKeyId='alias/aws/s3')

我现在想使用 file_upload 方法将文件直接上传到 s3。我找不到如何将服务器端加密添加到file_upload方法中。file_upload方法可以采用 TransferConfig,但我没有看到任何设置加密的参数,但我确实在 S3Transfer 中看到它们。

我正在寻找这样的东西:

import boto3
s3 = boto3.resource('s3')
tc = boto3.s3.transfer.TransferConfig(ServerSideEncryption='aws:kms',
                                      SEKMSKeyId='alias/aws/s3')
s3.upload_file(file_name, 
               bucket, 
               object_name,
               Config=tc)

BOTO3 文档

  • file_upload
  • 传输配置

jarmod 的帮助下,我能够想出两种解决方案。

使用 boto3.s3.transfer.S3Transfer

import boto3
client = boto3.client('s3', 'us-west-2')
transfer = boto3.s3.transfer.S3Transfer(client=client)
transfer.upload_file(file_name,
                     bucket, 
                     key_name,
                     extra_args={'ServerSideEncryption':'aws:kms', 
                                 'SSEKMSKeyId':'alias/aws/s3'}
)

使用 s3.meta.client

import boto3
s3 = boto3.resource('s3')
s3.meta.client.upload_file(file_name, 
                           bucket, key_name, 
                           ExtraArgs={'ServerSideEncryption':'aws:kms',
                                      'SSEKMSKeyId':'alias/aws/s3'})
如果你想使用 s3 kms,

你不要在 boto3 api 中传递 SSEKMSKeyId,默认情况下,它使用 s3 kms 密钥。

    import boto3
    s3 = boto3.client('s3')
    content = '64.242.88.10 - - [07/Mar/2004:16:06:51 -0800] "GET /twiki/bin/rdiff/TWiki/NewUserTemplate?rev1=1.3&rev2=1.2 HTTP/1.1" 200 4523'
   s3.put_object(Bucket=testbucket, Key='ex31/input.log', Body=content,ServerSideEncryption='aws:kms')

最新更新