我使用 terraform 创建了一个 aws ec2 实例,现在我无法 ssh 到机器

问题描述 投票:0回答:1

我使用 terraform 创建了一个 aws ec2 实例,现在我无法 ssh 进入机器 这是我使用的 terraform 代码,我认为正确的区域

resource "aws_key_pair" "test-terraform" {
  key_name   = "test-terraform"
  public_key = file("~/Documents/key-pairs/test-terraform.pub")
}

resource "aws_vpc" "main" {
  cidr_block       = "10.0.0.0/16"
  instance_tenancy = "default"

  tags = {
    Name = "main"
  }
}

resource "aws_subnet" "main_subnet" {
  vpc_id     = aws_vpc.main.id         # reference the related VPC id here
  cidr_block = "10.0.1.0/24"
  availability_zone = "us-east-1a"     # optional

  tags = {
    Name = "main_subnet"
  }
}

resource "aws_security_group" "main_security_group" {

  name = "main-security-group"
  description = "Security group for ec2 instances"
  vpc_id = aws_vpc.main.id     # reference the related VPC id 

  tags = {
    Name = "main_security_group"
  }

  # Allow all outbound traffic
  egress {
    from_port = 0
    to_port   = 0
    protocol = "-1"              
    cidr_blocks = ["0.0.0.0/0"]
  }

  # Allow SSH inbound traffic
  ingress {
    from_port = 0
    to_port   = 0
    protocol = "-1"
    cidr_blocks = ["0.0.0.0/0"] # You can restrict this to specific IP addresses for better security
  }

}

resource "aws_instance" "web_server" {
  ami           = "ami-080e1f13689e07408" # Update with your desired AMI ID
  instance_type = "t2.micro"

  vpc_security_group_ids = [aws_security_group.main_security_group.id]
  subnet_id = aws_subnet.main_subnet.id  # Associate with the public subnet
  associate_public_ip_address = true  # Allocate a public IP address to the instance
  key_name = aws_key_pair.test-terraform.key_name  # ti add jkey from referencing it, key must be generated locally and the public key must be referenced check the block below

  # Optional but good security measure
#   metadata_options {
#     http_tokens     = "required"  # Require the use of IMDSv2
#     http_put_response_hop_limit = 1  # Ensure only one hop for HTTP PUT requests
#   }

  # Add tags (optional)
  tags = {
    Name = "Web Server Instance"
  }
}

output "public_ip" {
  value = aws_instance.web_server.public_ip
}

我检查了网络似乎没问题, 即使 Aws 控制台也无法连接,这告诉我密钥不是问题。 这可能是一个愚蠢的错误,但期待解决方案

amazon-web-services networking amazon-ec2 ssh terraform
1个回答
0
投票

您的 Terraform 模板缺少入站和出站网络流量所需的一些内容,它们是:

  1. 互联网网关 (IGW)
  2. 公有子网的路由表条目,具有到 IGW 的默认路由

您可以轻松添加它们,如下所示:

resource "aws_internet_gateway" "igw" {
  vpc_id = aws_vpc.main.id
 
  tags = {
    Name = "VPC IGW"
  }
}

resource "aws_route_table" "rtb2" {
  vpc_id = aws_vpc.main.id
 
  route {
    cidr_block = "0.0.0.0/0"
    gateway_id = aws_internet_gateway.igw.id
  }
 
  tags = {
    Name = "Route Table 2 for IGW"
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.