# Terraform configuration to create an IAM user, group, and a custom policy,
# then attach the policy to the group and add the user to the group.

provider "aws" {
  region = "us-east-1"
}

# --- 1. Create IAM User ---
resource "aws_iam_user" "my_user" {
  name = "MyTerraformUser"
  tags = {
    Environment = "Dev"
  }
}

# --- 2. Create IAM Group ---
resource "aws_iam_group" "my_group" {
  name = "MyTerraformGroup"
}

# --- 3. Create Custom IAM Policy (S3 Read-Only) ---
data "aws_iam_policy_document" "s3_read_only" {
  statement {
    actions = [
      "s3:Get*",
      "s3:List*",
    ]
    resources = ["*"] # Grants read-only access to all S3 resources
  }
}

resource "aws_iam_policy" "s3_read_only_policy" {
  name        = "MyTerraformS3ReadOnlyPolicy"
  description = "Grants read-only access to S3 buckets"
  policy      = data.aws_iam_policy_document.s3_read_only.json
}

# --- 4. Attach Policy to Group ---
resource "aws_iam_group_policy_attachment" "group_policy_attachment" {
  group      = aws_iam_group.my_group.name
  policy_arn = aws_iam_policy.s3_read_only_policy.arn
}

# --- 5. Add User to Group ---
resource "aws_iam_group_membership" "user_group_membership" {
  name = "my-user-group-membership"
  users = [
    aws_iam_user.my_user.name,
  ]
  group = aws_iam_group.my_group.name
}

# --- Outputs ---
output "iam_user_name" {
  value       = aws_iam_user.my_user.name
  description = "The name of the IAM user."
}

output "iam_group_name" {
  value       = aws_iam_group.my_group.name
  description = "The name of the IAM group."
}

output "iam_policy_arn" {
  value       = aws_iam_policy.s3_read_only_policy.arn
  description = "The ARN of the custom S3 read-only policy."
}
