# Terraform configuration to create an EFS file system and a mount target.

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

# --- 1. Data Source for Default VPC and Subnet ---
data "aws_vpc" "default" {
  default = true
}

data "aws_subnet" "default" {
  vpc_id            = data.aws_vpc.default.id
  availability_zone = "us-east-1a" # Specify an AZ for the mount target
  filter {
    name   = "default_for_az"
    values = ["true"]
  }
}

# --- 2. Create Security Group for EFS ---
resource "aws_security_group" "efs_sg" {
  name        = "MyTerraformEFS_SG"
  description = "Allow NFS traffic for EFS"
  vpc_id      = data.aws_vpc.default.id

  ingress {
    description = "Allow NFS from VPC"
    from_port   = 2049
    to_port     = 2049
    protocol    = "tcp"
    cidr_blocks = [data.aws_vpc.default.cidr_block] # Allow from within the VPC
  }

  egress {
    from_port   = 0
    to_port     = 0
    protocol    = "-1"
    cidr_blocks = ["0.0.0.0/0"]
  }

  tags = {
    Name = "MyTerraformEFS_SG"
  }
}

# --- 3. Create EFS File System ---
resource "aws_efs_file_system" "my_efs" {
  creation_token = "my-terraform-efs-filesystem" # Unique string for idempotency
  performance_mode = "generalPurpose"
  throughput_mode  = "bursting"
  encrypted        = true

  tags = {
    Name = "MyTerraformEFSFileSystem"
  }
}

# --- 4. Create Mount Target ---
resource "aws_efs_mount_target" "my_mount_target" {
  file_system_id  = aws_efs_file_system.my_efs.id
  subnet_id       = data.aws_subnet.default.id
  security_groups = [aws_security_group.efs_sg.id]
}

# --- Outputs ---
output "efs_file_system_id" {
  value       = aws_efs_file_system.my_efs.id
  description = "The ID of the EFS file system."
}

output "efs_mount_target_id" {
  value       = aws_efs_mount_target.my_mount_target.id
  description = "The ID of the EFS mount target."
}

output "efs_dns_name" {
  value       = aws_efs_file_system.my_efs.dns_name
  description = "The DNS name of the EFS file system."
}
