Debug School

Steed47
Steed47

Posted on

Terraform-Day2-2

# Write a terraform code would create following resources


#Resource to create a SSH private key
resource "tls_private_key" "kahwo_key" {
  algorithm = "RSA"
  rsa_bits  = 4096
}

resource "aws_key_pair" "kahwo_key_pair" {
  key_name   = "kahwo-keypair"
  public_key = tls_private_key.kahwo_key.public_key_openssh
}



# - Display a pvt on Console

output "private_key" {
  value = tls_private_key.kahwo_key.private_key_pem
  sensitive = true
}

# - Create a Security group must open 80 Port

resource "aws_security_group" "NSG-kahwo" {
  name        = "kahwo-security-group"
  description = "Open Port 80"

  # Ingress rule for HTTP (port 80)
  ingress {
    from_port   = 80
    to_port     = 80
    protocol    = "tcp"
    cidr_blocks = ["0.0.0.0/0"] 
  }

  # Ingress rule for SSH (port 22)
  ingress {
    from_port   = 22
    to_port     = 22
    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"]
  }



}


# - Create a Ec2 instance Ubuntu using the same Key & SG which you created above.
resource "aws_instance" "create_ec2" {
  ami           = "ami-053b0d53c279acc90"
  instance_type = "t2.micro"
  key_name      = aws_key_pair.kahwo_key_pair.key_name
  vpc_security_group_ids = [aws_security_group.NSG-kahwo.id]
  tags = {
    Name = "kahwo"
  }

  connection {
      type     = "ssh"
      user     = "ubuntu"
      private_key = tls_private_key.kahwo_key.private_key_pem
      #host = aws_instance.web.public_ip
      host = self.public_ip
  }

  provisioner "remote-exec" {
    inline = [
      "sudo apt-get update",
      "sudo apt-get install apache2 -y",
      "sudo systemctl start apache2"
    ]
  }
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)