AWS 不提供官方 CloudFormation 资源来在 S3 存储桶中创建对象。但是,您可以创建一个 Lambda-backed Custom Resource 来使用 AWS 开发工具包执行此功能,事实上,gilt/cloudformation-helpers GitHub 存储库提供了一个现成的自定义资源来执行此操作。
与任何自定义资源设置一样有点冗长,因为您需要先部署 Lambda 函数和 IAM 权限,然后将其作为堆栈模板中的自定义资源引用。
首先,将Lambda::Function 和关联的IAM::Role 资源添加到您的堆栈模板:
"S3PutObjectFunctionRole": {
"Type": "AWS::IAM::Role",
"Properties": {
"AssumeRolePolicyDocument": {
"Version" : "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Principal": {
"Service": [ "lambda.amazonaws.com" ]
},
"Action": [ "sts:AssumeRole" ]
}
]
},
"ManagedPolicyArns": [
{ "Ref": "RoleBasePolicy" }
],
"Policies": [
{
"PolicyName": "S3Writer",
"PolicyDocument": {
"Version" : "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"s3:DeleteObject",
"s3:ListBucket",
"s3:PutObject"
],
"Resource": "*"
}
]
}
}
]
}
},
"S3PutObjectFunction": {
"Type": "AWS::Lambda::Function",
"Properties": {
"Code": {
"S3Bucket": "com.gilt.public.backoffice",
"S3Key": "lambda_functions/cloudformation-helpers.zip"
},
"Description": "Used to put objects into S3.",
"Handler": "aws/s3.putObject",
"Role": {"Fn::GetAtt" : [ "S3PutObjectFunctionRole", "Arn" ] },
"Runtime": "nodejs",
"Timeout": 30
},
"DependsOn": [
"S3PutObjectFunctionRole"
]
},
然后您可以使用 Lambda 函数作为自定义资源来创建您的 S3 对象:
"MyFolder": {
"Type": "Custom::S3PutObject",
"Properties": {
"ServiceToken": { "Fn::GetAtt" : ["S3PutObjectFunction", "Arn"] },
"Bucket": "mybucket",
"Key": "myfolder/"
}
},
除了Bucket 和Key(参见docs)之外,您还可以通过添加Body 参数来使用相同的自定义资源来编写基于字符串的S3 对象。