我正在构建一个 CDK 库,并尝试将一个 zip 文件夹上传到 S3,我可以稍后将其用于 Lambda 部署。我在网上找到了很多使用方法
aws_s3_deployment
.
该构造的问题在于它加载了 zip 的内容而不是 zip 本身。我试图将一个 zip 压缩到一个 zip 中,但这不起作用。我也试过压缩一个文件夹,但这也不起作用。我看到的行为是 S3 中没有显示任何内容,CDK 也没有错误。还有另一种方法可以将 zip 加载到 S3 吗?
您正在寻找的是 aws-s3-assets 模块。它允许您将目录(将被压缩)或常规文件定义为 CDK 将为您上传到 S3 的资产。使用attributes你可以参考资产。
文档有这个例子:
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')
});
为了将 zip 文件上传到给定的存储桶,我最终使用了带有自定义
BucketDeployment
的 ILocalBundling
。自定义捆绑器将压缩文件并将它们放在 assets 目录中供 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,
)
您现在可以使用
BucketDeployment
属性 extract
如下所示:
https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_s3_deployment.BucketDeployment.html
不幸的是,无法定义 zip 文件的名称。 CDK 将使用它的散列功能来命名。