I have created an EC2 instance and security group resource via Terraform file. However when I do,
curl http://<public IP>:8080
I get
curl: (7) Failed to connect to port 8080 after 8 ms: Couldn’t connect to server
Here is the tf file. How to fix this so I can access EC2 instance via the curl command?
provider "aws" {
region = "ap-southeast-2"
}
variable "server_port"{
type = number
description = "the port for HTTP"
default = 8080
}
resource "aws_instance" "name" {
ami = "ami-0dfb78957e4edea0c"
instance_type = "t2.large"
vpc_security_group_ids = [aws_security_group.instance.id]
user_data = <<-EOF
#!/bin/bash
echo "Hello, World" > index.html
nohup busybox httpd -f -p {var.server_port} &
EOF
user_data_replace_on_change = true
tags={
Name="terraform-example"
}
}
resource "aws_security_group" "instance"{
name="terraform-example-security-instance"
ingress {
from_port = var.server_port
to_port = var.server_port
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"]
ipv6_cidr_blocks = ["::/0"]
}
tags={
Name="terraform-example"
}
}
output "public_ip" {
value = aws_instance.name.public_ip
description ="The public IP address of EC2"
}
2
Answers
This needed egress set too. It is working now with this updated code.
This error has nothing to do with the terraform code or the way you craeted your instance. All your configurations are correct.
Check the actual server you are running inside the instance to check if it is running and accessible locally.