如何为EC2实例配置仅访问指定S3存储桶的权限角色?
Absolutely! You can absolutely tighten up that security by modifying your IAM role's policy to limit S3 access to just the buckets you need—this is core to following the least privilege principle, which is always a good call for AWS security.
Here's how to fix your over-broad configuration:
Replace the Full-Access Policy
Your current policy uses s3:* which opens the door to every S3 bucket in your account. Let's swap that for a targeted policy that only allows the actions your EC2 instance actually needs, restricted to your specific bucket.
Example Restrictive Policy
Use this template (update the bucket name and actions to match your use case):
{ "Version": "2012-10-17", "Statement": [ // Grants access to object-level operations (read/write/delete) in the bucket { "Effect": "Allow", "Action": [ "s3:GetObject", "s3:PutObject", "s3:DeleteObject" // Only include actions your EC2 instance requires—skip any you don't need! ], "Resource": [ "arn:aws:s3:::your-specific-bucket-name", "arn:aws:s3:::your-specific-bucket-name/*" ] }, // Optional: Add this if you need the instance to list objects in the bucket { "Effect": "Allow", "Action": "s3:ListBucket", "Resource": "arn:aws:s3:::your-specific-bucket-name" } ] }
Important Notes:
- Resource ARNs Explained: The first ARN targets the bucket itself (needed for actions like
ListBucket), while the second targets all objects inside the bucket (required forGetObject,PutObject, etc.). - Avoid Wildcards for Actions: Ditch
s3:*entirely. Only list the exact actions your instance uses—if it only needs to read files, removes3:PutObjectands3:DeleteObject. - Check for Conflicting Policies: Ensure no other policies attached to the IAM role grant broader S3 access—those could take precedence and bypass this restriction.
After applying this updated policy, your EC2 instance will only be able to interact with the specific S3 bucket(s) you defined, eliminating that security risk.
内容的提问来源于stack exchange,提问作者NeoSennin

