如何在CloudFormation::Init的files步骤读取KMS加密的S3存储桶文件?
I’ve hit this exact snag before—let’s walk through how to get your stack working with KMS-encrypted S3 buckets:
Why This Happens
CloudFormation::Init relies on the AWS SDK under the hood, and by default, it might not use AWS Signature Version 4 (SigV4) for S3 requests. KMS-encrypted buckets mandate SigV4 because it’s more secure and required for any operations involving KMS keys. Unencrypted buckets don’t enforce this, which is why they work without extra config.
Step-by-Step Fix
1. Update Your CloudFormation::Init Files Configuration
You need to explicitly tell CloudFormation::Init to use SigV4 when pulling files from the encrypted bucket. Add a metadata section under your file definition, setting aws:s3:signatureVersion to v4.
Here’s your modified template fragment (expanded to show the critical CloudFormation::Init part):
{ "AWSTemplateFormatVersion": "2010-09-09", "Resources": { "ProcessingMachine1": { "Type": "AWS::EC2::Instance", "Metadata": { "AWS::CloudFormation::Init": { "config": { "files": { "/path/to/your/target/file": { "source": "s3://your-kms-encrypted-bucket/path/to/source/file", "metadata": { "aws:s3:signatureVersion": "v4" }, "mode": "000644", "owner": "root", "group": "root" } } } } }, "Properties": { // Add your instance properties (AMI, instance type, IAM role, etc.) here } } } }
2. Double-Check IAM Permissions
Make sure the IAM role attached to your EC2 instance has two key permissions:
- S3 Access:
s3:GetObjectfor the specific file or prefix in your encrypted bucket - KMS Access:
kms:Decryptfor the KMS key used to encrypt the bucket (this is non-negotiable—even with S3 permissions, the instance needs to decrypt the object content)
Example IAM policy snippet:
{ "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Action": "s3:GetObject", "Resource": "arn:aws:s3:::your-kms-encrypted-bucket/*" }, { "Effect": "Allow", "Action": "kms:Decrypt", "Resource": "arn:aws:kms:us-east-1:123456789012:key/your-kms-key-id" } ] }
3. Test the Stack
Deploy your updated stack, then verify success:
- Check CloudFormation stack events for no errors
- Connect to the EC2 instance and confirm the file was downloaded to the target path
- If issues persist, check the
cfn-initlogs at/var/log/cfn-init.logon the instance for detailed troubleshooting info
内容的提问来源于stack exchange,提问作者Steve Robinson

