# Terraform configuration to launch a basic EC2 instance with necessary prerequisites.

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

# --- 1. Data Source for Latest Amazon Linux 2 AMI ---
data "aws_ami" "amazon_linux_2" {
  most_recent = true
  owners      = ["amazon"]

  filter {
    name   = "name"
    values = ["amzn2-ami-hvm-*-x86_64-gp2"]
  }

  filter {
    name   = "virtualization-type"
    values = ["hvm"]
  }
}

# --- 2. Create EC2 Key Pair ---
resource "tls_private_key" "ssh_key" {
  algorithm = "RSA"
  rsa_bits  = 4096
}

resource "aws_key_pair" "deployer" {
  key_name   = "MyTerraformKeyPair"
  public_key = tls_private_key.ssh_key.public_key_openssh
}

resource "local_file" "ssh_private_key" {
  content  = tls_private_key.ssh_key.private_key_pem
  filename = "${path.module}/${aws_key_pair.deployer.key_name}.pem"
  file_permission = "0400" # Set read-only permissions for the private key
}

# --- 3. Create Security Group ---
resource "aws_security_group" "instance_sg" {
  name        = "MyTerraformSecurityGroup"
  description = "Allow SSH and HTTP inbound traffic"
  vpc_id      = data.aws_vpc.default.id # Use default VPC

  ingress {
    description = "SSH from anywhere"
    from_port   = 22
    to_port     = 22
    protocol    = "tcp"
    cidr_blocks = ["0.0.0.0/0"]
  }

  ingress {
    description = "HTTP from anywhere"
    from_port   = 80
    to_port     = 80
    protocol    = "tcp"
    cidr_blocks = ["0.0.0.0/0"]
  }

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

  tags = {
    Name = "MyTerraformSecurityGroup"
  }
}

# Data source for default VPC
data "aws_vpc" "default" {
  default = true
}

# Data source for a default subnet in the default VPC
data "aws_subnet" "default" {
  vpc_id     = data.aws_vpc.default.id
  for_each   = data.aws_availability_zones.available.names
  filter {
    name   = "default_for_az"
    values = ["true"]
  }
  availability_zone = each.value
}

data "aws_availability_zones" "available" {
  state = "available"
}

# --- 4. Launch EC2 Instance ---
resource "aws_instance" "web_server" {
  ami           = data.aws_ami.amazon_linux_2.id
  instance_type = "t2.micro"
  key_name      = aws_key_pair.deployer.key_name
  vpc_security_group_ids = [aws_security_group.instance_sg.id]
  subnet_id     = tolist(data.aws_subnet.default)[0].id # Pick the first default subnet
  associate_public_ip_address = true # Assign a public IP

  tags = {
    Name = "MyTerraformInstance"
  }
}

# --- Outputs ---
output "instance_id" {
  value       = aws_instance.web_server.id
  description = "The ID of the EC2 instance."
}

output "public_ip" {
  value       = aws_instance.web_server.public_ip
  description = "The public IP address of the EC2 instance."
}

output "ssh_command" {
  value       = "ssh -i ${aws_key_pair.deployer.key_name}.pem ec2-user@${aws_instance.web_server.public_ip}"
  description = "SSH command to connect to the instance."
}
