【问题标题】:How to upload a zip to S3 with CDK如何使用 CDK 将 zip 上传到 S3
【发布时间】:2022-06-29 05:05:42
【问题描述】:

我正在构建一个 CDK 库,并尝试将一个 zip 文件夹上传到 S3,然后我可以稍后将其用于 Lambda 部署。我在网上找到了很多使用aws_s3_deployment的方向。

该构造的问题在于它加载的是 zip 的内容,而不是 zip 本身。我试图在一个拉链内拉一个拉链,但这不起作用。我也试过压缩一个文件夹,但这也不起作用。我看到的行为是 S3 中没有显示任何内容,并且 CDK 没有错误。还有其他方法可以将 zip 加载到 S3 吗?

【问题讨论】:

    标签: amazon-web-services amazon-s3 aws-lambda aws-cdk


    【解决方案1】:

    您正在寻找的是aws-s3-assets 模块。它允许您将目录(将被压缩)或常规文件定义为 CDK 将为您上传到 S3 的资产。使用attributes,您可以参考资产。

    documentation 有这个例子:

    import { Asset } from 'aws-cdk-lib/aws-s3-assets';
    
    // Archived and uploaded to Amazon S3 as a .zip file
    const directoryAsset = new Asset(this, "SampleZippedDirAsset", {
      path: path.join(__dirname, "sample-asset-directory")
    });
    
    // Uploaded to Amazon S3 as-is
    const fileAsset = new Asset(this, 'SampleSingleFileAsset', {
      path: path.join(__dirname, 'file-asset.txt')
    });
    

    【讨论】:

    • 您知道是否可以选择提供应该保存它的存储桶还是始终是 cdk-assets-bucket?
    • 我认为这不可能。虽然您可能会使用 CloudFormation 逃生舱盖覆盖某些内容 - 从未尝试过。
    【解决方案2】:

    为了将 zip 文件上传到给定的存储桶,我最终使用了 BucketDeployment 和自定义 ILocalBundling。自定义捆绑器将压缩文件并将它们放在资产目录中以供 CDK 上传。重要的是设置output_type=BundlingOutput.NOT_ARCHIVED,这样CDK就不会尝试解压文件了。

    @implements(ILocalBundling)
    class LocalBundling:
        @member(jsii_name="tryBundle")
        def try_bundle(self, output_dir: str, image: DockerImage,) -> bool:
            cwd = pathlib.Path.cwd()
    
            print(f"bundling to {output_dir}...")
            build_dir = f"{cwd}/directory/to"
            command = ["zip", "-r", f"{output_dir}/python.zip", f"zip"]
            print(command)
            output = subprocess.run(command, capture_output=True, check=True, cwd=build_dir)
            # print(output.stdout.decode("utf-8"))
            return True
    
    local_bundling = LocalBundling()
    s3_deployment.BucketDeployment(
        self,
        f"SomeIdForBucketDeployment",
        sources=[
            s3_deployment.Source.asset(
                "directory/to/zip",
                bundling=BundlingOptions(
                    command=['none'],
                    image=DockerImage.from_registry("lm"),
                    local=local_bundling,
                    output_type=BundlingOutput.NOT_ARCHIVED,
                ),
            )
        ],
        destination_bucket=some_bucket,
        destination_key_prefix=some_key_prefix,
    )
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-09-30
      • 1970-01-01
      • 2012-03-31
      • 1970-01-01
      • 2021-05-02
      • 2018-07-09
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多