# Terraform configuration to create an AWS CloudHSM cluster.

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

# --- 1. VPC and Subnet for CloudHSM ---
resource "aws_vpc" "cloudhsm_vpc" {
  cidr_block = "10.0.0.0/16"

  tags = {
    Name = "my-terraform-cloudhsm-vpc"
  }
}

resource "aws_subnet" "cloudhsm_subnet" {
  vpc_id            = aws_vpc.cloudhsm_vpc.id
  cidr_block        = "10.0.1.0/24"
  availability_zone = "us-east-1a"

  tags = {
    Name = "my-terraform-cloudhsm-subnet"
  }
}

# --- 2. Create Security Group for CloudHSM ---
resource "aws_security_group" "cloudhsm_sg" {
  name        = "MyTerraformCloudHSMSG"
  description = "Security Group for CloudHSM cluster"
  vpc_id      = aws_vpc.cloudhsm_vpc.id

  # Allow inbound traffic from itself (for cluster communication)
  ingress {
    from_port   = 0
    to_port     = 0
    protocol    = "-1"
    self        = true
  }

  # Allow outbound to anywhere (for management, updates, etc.)
  egress {
    from_port   = 0
    to_port     = 0
    protocol    = "-1"
    cidr_blocks = ["0.0.0.0/0"]
  }

  tags = {
    Name = "MyTerraformCloudHSMSG"
  }
}

# --- 3. Create CloudHSM Cluster ---
resource "aws_cloudhsm_v2_cluster" "main" {
  hsm_type    = "hsm1.medium" # Specify a valid HSM type
  subnet_ids  = [aws_subnet.cloudhsm_subnet.id]
  security_group_id = aws_security_group.cloudhsm_sg.id

  tags = {
    Name = "MyTerraformCloudHSMCluster"
  }
}

# --- Outputs ---
output "cloudhsm_cluster_id" {
  value       = aws_cloudhsm_v2_cluster.main.cluster_id
  description = "The ID of the CloudHSM cluster."
}

output "cloudhsm_cluster_state" {
  value       = aws_cloudhsm_v2_cluster.main.cluster_state
  description = "The state of the CloudHSM cluster."
}
