SSH by Terraform in EC2

This is the complete guide how to ssh by terraform

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

# Security Group allowing SSH access
resource "aws_security_group" "allow_ssh" {
  name        = "allow_ssh"
  description = "Allow SSH inbound traffic"

  ingress {
    from_port   = 22
    to_port     = 22
    protocol    = "tcp"
    cidr_blocks = ["0.0.0.0/0"]  # Adjust this for security (e.g., use your IP)
  }

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

  tags = {
    Name = "allow_ssh"
  }
}

# EC2 Instance creation
resource "aws_instance" "example" {
  ami           = "ami-0866a3c8686eaeeba"
  instance_type = "t2.micro"
  key_name      = "terraform_key"
  vpc_security_group_ids = [aws_security_group.allow_ssh.id]

  tags = {
    Name = "Terraform SSH Example"
  }
}

# SSH Connection using null_resource
resource "null_resource" "ssh" {
  provisioner "remote-exec" {
    connection {
      type        = "ssh"
      user        = "ubuntu"
      host        = aws_instance.example.public_ip
      private_key = file("C:/Users/sarth/Downloads/terraform_key.pem")
      timeout     = "5m"
    }

    inline = [
      "echo 'Hello from Terraform!' > /tmp/hello.txt",
      "sudo apt-get update -y",
    ]
  }

  depends_on = [aws_instance.example]
}

This help me in this and Chatgpt “https://stackoverflow.com/questions/59708577/can-i-ssh-into-my-ec2-instance-created-by-terraform