| 1 | terraform { |
| 2 | required_providers { |
| 3 | aws = { source = "hashicorp/aws", version = ">= 5.0" } |
| 4 | } |
| 5 | } |
| 6 | |
| 7 | variable "name" { |
| 8 | type = string |
| 9 | validation { |
| 10 | condition = can(regex("^[a-zA-Z0-9+=,.@_-]{1,59}$", var.name)) |
| 11 | error_message = "Use an exact IAM resource name." |
| 12 | } |
| 13 | } |
| 14 | |
| 15 | variable "deployment_bucket_arn" { |
| 16 | type = string |
| 17 | validation { |
| 18 | condition = can(regex("^arn:aws:s3:::[a-z0-9][a-z0-9.-]+$", var.deployment_bucket_arn)) |
| 19 | error_message = "Use the exact deployment bucket ARN." |
| 20 | } |
| 21 | } |
| 22 | |
| 23 | resource "aws_iam_user" "bootstrap" { |
| 24 | name = "${var.name}-root" |
| 25 | path = "/carlos/fence-writers/" |
| 26 | } |
| 27 | |
| 28 | resource "aws_iam_role" "writer" { |
| 29 | name = var.name |
| 30 | max_session_duration = 3600 |
| 31 | assume_role_policy = jsonencode({ |
| 32 | Version = "2012-10-17" |
| 33 | Statement = [{ |
| 34 | Effect = "Allow" |
| 35 | Action = "sts:AssumeRole" |
| 36 | Principal = { AWS = aws_iam_user.bootstrap.arn } |
| 37 | }] |
| 38 | }) |
| 39 | } |
| 40 | |
| 41 | resource "aws_iam_user_policy" "assume" { |
| 42 | name = "assume-own-fence-role" |
| 43 | user = aws_iam_user.bootstrap.name |
| 44 | policy = jsonencode({ |
| 45 | Version = "2012-10-17" |
| 46 | Statement = [{ |
| 47 | Effect = "Allow" |
| 48 | Action = "sts:AssumeRole" |
| 49 | Resource = aws_iam_role.writer.arn |
| 50 | }] |
| 51 | }) |
| 52 | } |
| 53 | |
| 54 | resource "aws_iam_role_policy" "fences" { |
| 55 | name = "create-termination-fences" |
| 56 | role = aws_iam_role.writer.id |
| 57 | policy = jsonencode({ |
| 58 | Version = "2012-10-17" |
| 59 | Statement = [{ |
| 60 | Effect = "Allow" |
| 61 | Action = "s3:PutObject" |
| 62 | Resource = "${var.deployment_bucket_arn}/control/box-fences/*" |
| 63 | Condition = { |
| 64 | StringEquals = { "s3:if-none-match" = "*" } |
| 65 | } |
| 66 | }, { |
| 67 | Effect = "Allow" |
| 68 | Action = "s3:GetObject" |
| 69 | Resource = "${var.deployment_bucket_arn}/control/box-fences/*" |
| 70 | }] |
| 71 | }) |
| 72 | } |
| 73 | |
| 74 | output "role_arn" { |
| 75 | value = aws_iam_role.writer.arn |
| 76 | } |
| 77 | output "bootstrap_user" { |
| 78 | value = aws_iam_user.bootstrap.name |
| 79 | } |
| 80 | |