Reputation: 361
I have made a static website hosting S3 bucket that is served by CloudFront. I would like to restrict bucket access directly only from CloudFront through Origin Access Identity.
I have tried to update the S3 bucket policy but it's showing an error:
Error putting S3 policy: MalformedPolicy: Invalid principal in policy status code: 400, request id
I'm trying to use the following policy:
resource "aws_s3_bucket_policy" "default" {
bucket = "${aws_s3_bucket.default.id}"
policy = <<EOF
{
"Version": "2008-10-17",
"Statement": [
{
"Sid": "2",
"Effect": "Allow",
"Principal": {
"AWS": "arn:aws:iam::cloudfront:user/CloudFront Origin Access Identity ${aws_cloudfront_origin_access_identity.origin_access_identity.id}"
},
"Action": "s3:*",
"Resource": "arn:aws:s3:::$/*"
}
]
}
EOF
}
Upvotes: 7
Views: 8079
Reputation: 56839
As mentioned in the [aws_cloudfront_origin_access_identity documentation] 1 the best way to do this is by generating an IAM policy document
with the aws_iam_policy_document
data source and then attaching that directly.
An example would look something like this:
data "aws_iam_policy_document" "s3_policy" {
statement {
actions = ["s3:GetObject"]
resources = ["${module.names.s3_endpoint_arn_base}/*"]
principals {
type = "AWS"
identifiers = ["${aws_cloudfront_origin_access_identity.origin_access_identity.iam_arn}"]
}
}
statement {
actions = ["s3:ListBucket"]
resources = ["${module.names.s3_endpoint_arn_base}"]
principals {
type = "AWS"
identifiers = ["${aws_cloudfront_origin_access_identity.origin_access_identity.iam_arn}"]
}
}
}
resource "aws_s3_bucket" "bucket" {
# ...
policy = "${data.aws_iam_policy_document.s3_policy.json}"
}
If you really want to hand craft the IAM policy as you are in the question then you just need something like this:
resource "aws_s3_bucket_policy" "default" {
bucket = "${aws_s3_bucket.default.id}"
policy = <<EOF
{
"Version": "2008-10-17",
"Statement": [
{
"Sid": "2",
"Effect": "Allow",
"Principal": {
"AWS": "${aws_cloudfront_origin_access_identity.origin_access_identity.iam_arn}"
},
"Action": "s3:*",
"Resource": "${aws_s3_bucket.default.arn}""
}
]
}
EOF
}
Upvotes: 9