Search code examples
amazon-web-servicesterraformterraform-provider-aws

Connecting to AWS EC2 with terraform and execute commands


I'm new to infrastructure. I'm trying to create an EC2 instance and execute commands using Terraform provisioners. However, when I apply the Terraform configuration, it times out.

$ ssh_keygen -f ./example -m PEM // this generate example.pub and example
provider "aws" {
  region = "us-west-2"
}

resource "aws_key_pair" "example" {
  key_name   = "keypair"
  public_key = file("./example.pub")
  tags = {
    Name = "Example Key Pair"
  }
}

resource "aws_instance" "web" {
  ami           = "ami-003634241a8fcdec0"
  instance_type = "t2.micro"
  key_name      = aws_key_pair.example.key_name
  tags = {
    Name = "Example EC2"
  }

  connection {
    type        = "ssh"
    host        = self.public_ip
    user        = "ubuntu"
    private_key = file("./example")
  }

  provisioner "file" {
    content     = "Hello World!"
    destination = "/home/ubuntu/example.txt"
  }

}

Solution

  • can you please add the following:

    provisioner "file" {
    source      = "example.txt"              # terraform machine
    destination = "/home/ubuntu/example.txt" # remote machine
    }
    

    before:

    provisioner "file" {
        content     = "Hello World!"
        destination = "/home/ubuntu/example.txt"
      }
    

    where "example.txt" is an empty file available on your Terraform machine?

    Does it hangs as well?