AWS 不提供官方 CloudFormation 资源来在 S3 存储桶中创建对象。但是,您可以创建一个Lambda 支持的自定义资源 http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/template-custom-resources-lambda.html使用 AWS SDK 执行此功能,实际上gilt/cloudformation-helpers https://github.com/gilt/cloudformation-helpers#put-s3-objectsGitHub 存储库提供了一个现成的自定义资源来完成此任务。
与任何自定义资源设置一样,它有点冗长,因为您需要首先部署 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/"
}
},
您还可以使用相同的自定义资源通过添加Body
参数除了Bucket
and Key
(参见docs https://github.com/gilt/cloudformation-helpers#put-s3-objects).