首页 > 解决方案 > 使用 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

标签: amazon-s3aws-lambdaboto3

解决方案


我已经使用 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 中工作正常。


推荐阅读