LocalStack S3无法通过boto3访问,求代码连接解决方案
问题描述
我已通过Docker成功运行LocalStack,对应的docker-compose配置如下:
services: localstack: image: localstack/localstack:latest network_mode: host environment: - SERVICES=s3 - AWS_DEFAULT_REGION=eu-west-1 - HOSTNAME_EXTERNAL=localhost - DEBUG=1 ports: - '4566-4583:4566-4583'
我可以通过awslocal工具完成创建存储桶、上传文件等操作,示例如下:
# 创建存储桶 awslocal s3 mb s3://test > make_bucket: test # 上传测试文件至S3 awslocal s3 cp test.txt s3://test > upload: ./test.txt to s3://test/test.txt # 检查文件是否上传成功 awslocal s3 ls s3://test > 2022-12-25 22:18:44 10 test.txt
接下来我尝试通过代码连接,编写了简单的boto3 Python脚本,但运行时提示错误Unable to locate credentials。我试过使用aws configure,但不知道LocalStack S3的访问密钥和秘密密钥,陷入困境。Python脚本代码如下:
import boto3 from botocore.exceptions import ClientError import os ddb1 = boto3.client('s3', endpoint_url='http://localhost.localstack.cloud:4566') def upload_file(file_name, bucket, object_name=None): """ Upload a file to a S3 bucket. """ try: if object_name is None: object_name = os.path.basename(file_name) response = ddb1.upload_file( file_name, bucket, object_name) except ClientError: print('Could not upload file to S3 bucket.') raise else: return response upload_file("testdata/test.txt", "sample")
希望得到无需使用awslocal,直接通过代码连接LocalStack S3的解决方法。
解决方法
LocalStack对AWS凭证没有实际校验要求,只要提供非空的密钥即可。以下是几种可行的解决方案:
1. 代码内直接指定凭证和区域
修改boto3客户端初始化代码,显式传入任意非空的密钥值,同时指定区域:
import boto3 from botocore.exceptions import ClientError import os # 显式配置LocalStack连接参数 ddb1 = boto3.client( 's3', endpoint_url='http://localhost.localstack.cloud:4566', aws_access_key_id='test', aws_secret_access_key='test', region_name='eu-west-1' ) def upload_file(file_name, bucket, object_name=None): """ Upload a file to a S3 bucket. """ try: if object_name is None: object_name = os.path.basename(file_name) response = ddb1.upload_file( file_name, bucket, object_name) except ClientError: print('Could not upload file to S3 bucket.') raise else: return response upload_file("testdata/test.txt", "sample")
2. 通过环境变量配置
在运行脚本前,设置以下环境变量,boto3会自动读取这些配置:
export AWS_ACCESS_KEY_ID=test export AWS_SECRET_ACCESS_KEY=test export AWS_DEFAULT_REGION=eu-west-1
设置完成后直接运行原脚本即可,无需修改代码。
3. 使用本地AWS配置文件
在~/.aws/credentials文件中添加LocalStack专属配置:
[localstack] aws_access_key_id = test aws_secret_access_key = test
在~/.aws/config文件中添加区域配置:
[profile localstack] region = eu-west-1
之后在代码中指定使用该配置文件:
ddb1 = boto3.client( 's3', endpoint_url='http://localhost.localstack.cloud:4566', profile_name='localstack' )
注意事项
- LocalStack的S3端点也可以直接使用
http://localhost:4566,与localhost.localstack.cloud效果一致 - 确保目标存储桶
sample已提前创建(可通过awslocal或代码调用创建接口),否则会触发存储桶不存在的错误
内容的提问来源于stack exchange,提问作者talkdatatome
相关产品推荐
相关产品推荐

