EC2 实例中的 httpserver 通过 terraform

httpserver in EC2 instance via terraform

terraform {
  required_providers {
    aws = {
      version = "~>3.27"
      source  = "hashicorp/aws"
    }
  }
}


provider "aws" {
  profile = "default"
  region  = "us-west-2"

}

variable "tag_name" {
  type = string

}

resource "aws_instance" "app_server" {
  ami                    = "ami-830c94e3"
  instance_type          = "t2.micro"
  vpc_security_group_ids = [aws_security_group.allow_port_8080.id]
  user_data              = <<-EOF
  
    #!/bin/bash
# Use this for your user data (script from top to bottom)
# install httpd (Linux 2 version)
yum update -y
yum install -y httpd
systemctl start httpd
systemctl enable httpd
echo "<h1>Hello World from $(hostname -f)</h1>" > /var/www/html/index.html
      EOF
  tags = {
    Name = var.tag_name
  }
}

resource "aws_security_group" "allow_port_8080" {
  name = "allow_port_8080"


  ingress {

    from_port   = 8080
    to_port     = 8080
    protocol    = "tcp"
    cidr_blocks = ["0.0.0.0/0"]

  }


}

这是创建的地形文件。我想在我的 EC2 实例中设置 http 服务器,然后通过 ipv4 public IP 访问它。 但是 http://publicip:8080,给出错误 无法访问此站点

我试过如下修改

user_data              = <<-EOF
  
    #!/bin/bash

    echo "<h1>Hello World</h1>" > index.html
    nohup busybox httpd -f -p 8080 
      EOF

我在关注 https://www.youtube.com/watch?v=0i-Q6ZMDtlQ&list=PLqq-6Pq4lTTYwjFB9E9aLUJhTBLsCF0p_&index=32

谢谢

您的 aws_security_group 不允许任何传出流量 ,因此您无法在其上安装 httpd。您 have to 明确允许传出流量:

resource "aws_security_group" "allow_port_8080" {
  name = "allow_port_8080"


  ingress {

    from_port   = 8080
    to_port     = 8080
    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"]
  }
}