amazon-s3 - 使用 lambda(boto 脚本)的跨账户 s3 存储桶同步
问题描述
我需要同步不同账户中的 s3 存储桶。为此,我使用存储桶策略创建 2 个存储桶,并使用 iam 策略和 s3 事件触发器创建 Lambda 函数。
我通过 CLI 尝试过。任何人都可以帮助编写机器人脚本来同步存储桶
我正在尝试下面的 lambda- 代码
logger = logging.getLogger()
logger.setLevel(logging.INFO)
def sync_command(command):
command_list = command.split(' ')
try:
logger.info("Running shell command: \"{}\"".format(command))
result = subprocess.run(command_list, stdout=subprocess.PIPE);
logger.info("Command output:\n---\n{}\n---".format(result.stdout.decode('UTF-8')))
except Exception as e:
logger.error("Exception: {}".format(e))
return False
return True
def lambda_handler(event, context):
logger.info(event);
SOURCE_BUCKET = os.environ['source']
print('SOURCE_BUCKET:', SOURCE_BUCKET)
TARGET_BUCKET = os.environ['target']
print('TARGET_BUCKET:', TARGET_BUCKET)
sync_command("aws s3 sync s3://source-bucket/ s3://destination-bucket/")
但这显示错误Exception: [Errno 2] No such file or directory: 'aws': 'aws
解决方案
我已经使用 bob 脚本做到了,这里是代码
import subprocess
import logging
import boto3
def check(bucket, key):
s3client = boto3.client("s3")
s3 = boto3.resource('s3')
copy_source = {
'Bucket': bucket,
'Key': key
}
print("key",key)
bucket = s3.Bucket('target_bucket')
bucket.copy(copy_source,key)
def lambda_handler(event, context):
ev = event["Records"]
bucketName = ev[0]["s3"]["bucket"]["name"]
keyName = ev[0]["s3"]["object"]["key"]
check(bucketName,keyName)
在 lambda 中工作正常。
推荐阅读
- java - 如何解决这个 90 或 -90 旋转问题
- python - 在一行中写入 Pandas DataFrame 的不同列?
- python - __init__() 为参数“crescator”获得了多个值
- python - 如何处理flask-classful中的http错误?
- javascript - 如何使用js比较数组并创建最终数组?
- angular - 从 Ionic Cordova 生成 APK
- java - 分类器没有伴随对象,因此必须在此处初始化
- java - 如何访问三位整数中的第二个字符?
- cmake - 您可以从另一个文件中包含一个通用的 cmake 最小值吗?
- icalendar - 日历邀请在某些平台而不是其他平台上工作