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"
}
}
2
Answers
can you please add the following:
before:
where "example.txt" is an empty file available on your Terraform machine?
Does it hangs as well?
The direct problem here was (based on comments on the other answer) an incorrect security group configuration, which is a common cause of problems with provisioners and one of the reasons why Provisioners are a last resort.
This seems to be an example of Passing data into virtual machines and other compute resources, in which case the documentation recommends against using provisioners and instead using the
user_data
oruser_data_base64
arguments ofaws_instance
, which will pass data to the EC2 instance indirectly through the EC2 API, rather than directly over SSH. That avoids the need for any direct network connectivity between Terraform and the EC2 instance, so incorrect security group rules cannot prevent it from working.Exactly how to use that will depend on what software is installed in the AMI you have chosen here, but most standard Linux distribution AMIs use the software cloud-init to handle system configuration tasks such as handling the
user_data
argument. If you are using an AMI which has cloud-init installed then the following official tutorial shows how to use it: