terraform.aws-baseline-infra/modules/terraform-setup/main.tf

120 lines
2.7 KiB
Terraform
Raw Normal View History

resource "aws_s3_bucket" "s3bucket" {
bucket = var.bucket-name
}
resource "aws_s3_bucket_public_access_block" "s3-public-access-settings" {
depends_on = [aws_s3_bucket.s3bucket]
bucket = aws_s3_bucket.s3bucket.id
block_public_acls = true
block_public_policy = true
ignore_public_acls = true
restrict_public_buckets = true
}
resource "aws_s3_bucket_ownership_controls" "bucket-ownership-setting" {
depends_on = [aws_s3_bucket_public_access_block.s3-public-access-settings]
bucket = aws_s3_bucket.s3bucket.id
rule {
object_ownership = "BucketOwnerPreferred"
}
}
resource "aws_s3_bucket_lifecycle_configuration" "bucket-lifecycle-config" {
count = var.bucket-enable-lifecycle ? 1 : 0
bucket = aws_s3_bucket.s3bucket.bucket
rule {
id = "default"
status = "Enabled"
dynamic "noncurrent_version_expiration" {
for_each = var.enable-bucket-versioning ? [1] : []
content {
noncurrent_days = 90
}
}
dynamic "expiration" {
for_each = var.bucket-retain-days > 0 ? [1] : []
content {
days = var.bucket-retain-days
}
}
transition {
days = var.transition-ia-days
storage_class = "STANDARD_IA"
}
}
}
resource "aws_s3_bucket_versioning" "bucket-versioning" {
count = var.enable-bucket-versioning ? 1 : 0
bucket = aws_s3_bucket.s3bucket.id
versioning_configuration {
status = "Enabled"
}
}
resource "aws_s3_bucket_server_side_encryption_configuration" "bucket-encryption" {
bucket = aws_s3_bucket.s3bucket.bucket
rule {
apply_server_side_encryption_by_default {
sse_algorithm = "AES256"
}
}
}
resource "aws_s3_bucket_acl" "bucket-acl" {
bucket = aws_s3_bucket.s3bucket.bucket
acl = var.bucket-acl
}
resource "aws_s3_bucket_policy" "bucket-policy" {
bucket = aws_s3_bucket.s3bucket.bucket
2022-08-17 16:01:26 +08:00
policy = <<EOT
{
"Id": "policy01",
"Version": "2012-10-17",
"Statement": [
{
"Sid": "AllowFullAccessFromBastion",
"Action": "s3:*",
"Effect": "Allow",
"Resource": [
"arn:aws:s3:::${var.bucket-name}/*",
"arn:aws:s3:::${var.bucket-name}-tfstate"
2022-08-17 16:01:26 +08:00
],
"Principal": {
"AWS": [
"arn:aws:iam::${data.aws_caller_identity.this.account_id}:root"
]
}
}
]
}
EOT
}
resource "aws_dynamodb_table" "tfstate-lock-table" {
name = var.ddb-table-name
billing_mode = "PAY_PER_REQUEST"
hash_key = "LockID"
point_in_time_recovery {
enabled = true
}
# If enabled is false then server-side encryption is set to AWS owned CMK (shown as DEFAULT in the AWS console)
server_side_encryption {
enabled = false
}
attribute {
name = "LockID"
type = "S"
}
}
data aws_caller_identity this {}