brikis98 / terraform-up-and-running-code

Code samples for the book "Terraform: Up & Running" by Yevgeniy Brikman
http://www.terraformupandrunning.com/
MIT License
2.83k stars 1.9k forks source link

EC2 instance not responding on port 8080 #101

Closed G0d3r closed 1 year ago

G0d3r commented 1 year ago

Hello everyone! I’m Ernest and I’m currently reading the book Terraform Up & Running 2nd version. I noted an issue when I wanted to use created EC2 instance on AWS and the public IPv4 address which does not work at all.

I am stuck with this problem for a couple of days now and I can’t find any information on the Internet. I noted also that many readers have the same issue when I was searching for the answer.

I used the source code which is the book but unfortunately, it does not work. I decided to correct a little the source code which is in book and now it looks as below but still iPv4 it does not respond. screenshot-1

sceenshot-2
provider "aws" {
  region = "eu-central-1"
}

resource "aws_security_group" "instance" {
  name = "aws-terraform-example-instance"
 ingress {
    from_port        = 8080
    to_port          = 8080
    protocol         = "tcp"
    cidr_blocks      = ["0.0.0.0/0"]
  }

   ingress {
    from_port        = 80
    to_port          = 80
    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    = "ALL"
    cidr_blocks = ["0.0.0.0/0"]
  }
}

resource "aws_instance" "example" {
  ami           = "ami-08f13e5792295e1b2"
  instance_type = "t2.micro"

  user_data = <<-EOF
                #!/bin/bash
                echo "Hello, World 2" > index.html
                nohup python3 -m http.server 8080 &
                EOF
  tags = {
    Name = "aws-terraform-example"
  }
}

output "public_ip" {
  value = "${aws_instance.example.public_ip}"
  description = "Public IP address"
}

Please help.

brikis98 commented 1 year ago

It looks like you created a security group, but you didn't actually attach it to your EC2 instance! You need to set the vpc_security_group_ids parameter on the aws_instance resource:

resource "aws_instance" "example" {
  ami           = "ami-08f13e5792295e1b2"
  instance_type = "t2.micro"

  user_data = <<-EOF
                #!/bin/bash
                echo "Hello, World 2" > index.html
                nohup python3 -m http.server 8080 &
                EOF
  tags = {
    Name = "aws-terraform-example"
  }

  # This attaches your security group to the EC2 instance
  vpc_security_group_ids = aws_security_group.instance.id
}
G0d3r commented 1 year ago

Thank you @brikis98 indeed, now it works! I missed that for some reason when I read this book.

brikis98 commented 1 year ago

Great to hear! Thanks for following up.