chatbot / deploy / main.tf
main.tf
Raw
provider "aws" {
  region = "us-east-1"
}

variable "ssh_key_path" {
  description = "Path to the SSH private key for connecting to the EC2 instance"
  type        = string
  default     = "~/.ssh/id_rsa" // Default path to the private key
}

variable "local_env_file" {
    description = "Path to local env file"
    type = string
    default = "../.env.local"
}

resource "aws_key_pair" "deploy" {
  key_name   = "devops-key"
  public_key = file("~/.ssh/id_rsa.pub") // Ensure you have this public key available
}

resource "aws_security_group" "deploy" {
  name_prefix = "deploy"

  ingress {
    from_port   = 80
    to_port     = 80
    protocol    = "tcp"
    cidr_blocks = ["0.0.0.0/0"]
  }
  
  ingress {
    from_port   = 443
    to_port     = 443
    protocol    = "tcp"
    cidr_blocks = ["0.0.0.0/0"]
  }

  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"]
  }
}

resource "aws_instance" "deploy" {
  ami           = "ami-006dcf34c09e50022" // Amazon Linux 2 AMI
  instance_type = "t2.micro"
  key_name      = aws_key_pair.deploy.key_name // Use the created key pair
  vpc_security_group_ids = [
    aws_security_group.deploy.id,
  ]
  user_data = <<-EOF
              #!/bin/bash
              yum install -y docker
              systemctl enable docker
              systemctl start docker
              sudo chown $USER /var/run/docker.sock
              EOF
}

resource "null_resource" "upload_env_file" {
  depends_on = [aws_instance.deploy]

  provisioner "local-exec" {
    command = <<-EOT
      scp -i ${var.ssh_key_path} -o StrictHostKeyChecking=no ${var.local_env_file} ec2-user@${aws_instance.deploy.public_ip}:/home/ec2-user/.env.local
      ssh -i ${var.ssh_key_path} -o StrictHostKeyChecking=no ec2-user@${aws_instance.deploy.public_ip} 'sudo docker run -d --rm -p 80:3000 --env-file /home/ec2-user/.env.local --name chatbot nicksome/headstarter-ai-chatbot && exit'
    EOT
  }

  triggers = {
    instance_id = aws_instance.deploy.id
  }
}

output "public_ip" {
  value = aws_instance.deploy.public_ip
}