Created
May 9, 2021 06:26
-
-
Save mtinsley/c58a4bde1123e1eda9426d68e4e1ba7e to your computer and use it in GitHub Desktop.
Terraform for remote state S3 bucket + DynamoDB table for locks
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
provider "aws" { | |
region = "us-west-2" | |
} | |
# S3 bucket for tfstate | |
resource "aws_s3_bucket" "terraform_state" { | |
bucket = "tfstate" | |
acl = "private" | |
versioning { | |
enabled = true | |
} | |
lifecycle { | |
prevent_destroy = true | |
} | |
server_side_encryption_configuration { | |
rule { | |
apply_server_side_encryption_by_default { | |
sse_algorithm = "AES256" | |
} | |
} | |
} | |
tags = { | |
Name = "Terraform State" | |
} | |
} | |
# Prevent public access | |
resource "aws_s3_bucket_public_access_block" "terraform_state_access_block" { | |
bucket = aws_s3_bucket.terraform_state.id | |
block_public_acls = true | |
block_public_policy = true | |
ignore_public_acls = true | |
restrict_public_buckets = true | |
} | |
# Require encryption | |
resource "aws_s3_bucket_policy" "terraform_state_policy" { | |
bucket = aws_s3_bucket.terraform_state.id | |
policy = <<EOF | |
{ | |
"Version": "2012-10-17", | |
"Id": "RequireEncryption", | |
"Statement": [ | |
{ | |
"Sid": "RequireEncryptedTransport", | |
"Effect": "Deny", | |
"Action": ["s3:*"], | |
"Resource": ["arn:aws:s3:::${aws_s3_bucket.terraform_state.bucket}/*"], | |
"Condition": { | |
"Bool": { | |
"aws:SecureTransport": "false" | |
} | |
}, | |
"Principal": "*" | |
}, | |
{ | |
"Sid": "RequireEncryptedStorage", | |
"Effect": "Deny", | |
"Action": ["s3:PutObject"], | |
"Resource": ["arn:aws:s3:::${aws_s3_bucket.terraform_state.bucket}/*"], | |
"Condition": { | |
"StringNotEquals": { | |
"s3:x-amz-server-side-encryption": "AES256" | |
} | |
}, | |
"Principal": "*" | |
} | |
] | |
} | |
EOF | |
} | |
# Dynamodb table for locking | |
resource "aws_dynamodb_table" "terraform_state_lock" { | |
name = "terraform-state-lock" | |
read_capacity = 1 | |
write_capacity = 1 | |
hash_key = "LockID" | |
attribute { | |
name = "LockID" | |
type = "S" | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment