Skip to content

Instantly share code, notes, and snippets.

@ronaldroe
Created December 6, 2024 05:06
Show Gist options
  • Save ronaldroe/84aeb641a18540ee09d6de43b82c075c to your computer and use it in GitHub Desktop.
Save ronaldroe/84aeb641a18540ee09d6de43b82c075c to your computer and use it in GitHub Desktop.

Revisions

  1. ronaldroe created this gist Dec 6, 2024.
    84 changes: 84 additions & 0 deletions S3_bucket_static_serve_with_iam.tf
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,84 @@
    resource "aws_s3_bucket" "static_website" {
    bucket = "your-static-website-bucket"

    acl = "private"

    website {
    index_document = "index.html"
    error_document = "error.html"
    }
    }

    resource "aws_iam_role" "s3_access_role" {
    name = "S3AccessRole"

    assume_role_policy = <<EOF
    {
    "Version": "2012-10-17",
    "Statement": [
    {
    "Action": "sts:AssumeRole",
    "Principal": {
    "Service": "ec2.amazonaws.com"
    },
    "Effect": "Allow"
    }
    ]
    }
    EOF
    }

    resource "aws_iam_policy" "s3_access_policy" {
    name = "S3AccessPolicy"

    policy = <<EOF
    {
    "Version": "2012-10-17",
    "Statement": [
    {
    "Action": [
    "s3:GetObject",
    "s3:ListBucket"
    ],
    "Effect": "Allow",
    "Resource": [
    "arn:aws:s3:::your-static-website-bucket",
    "arn:aws:s3:::your-static-website-bucket/*"
    ]
    }
    ]
    }
    EOF
    }

    resource "aws_iam_role_policy_attachment" "s3_access_role_policy_attachment" {
    role = aws_iam_role.s3_access_role.name
    policy_arn = aws_iam_policy.s3_access_policy.arn
    }

    resource "aws_s3_bucket_policy" "static_website_policy" {
    bucket = aws_s3_bucket.static_website.id

    policy = <<EOF
    {
    "Version": "2012-10-17",
    "Statement": [
    {
    "Sid": "AllowS3Access",
    "Effect": "Allow",
    "Principal": {
    "AWS": "arn:aws:iam::${aws_account_id}:role/S3AccessRole"
    },
    "Action": [
    "s3:GetObject",
    "s3:ListBucket"
    ],
    "Resource": [
    "arn:aws:s3:::your-static-website-bucket",
    "arn:aws:s3:::your-static-website-bucket/*"
    ]
    }
    ]
    }
    EOF
    }