
在 Ubuntu 18.04 上使用 Terraform v1.0.11
在terraform apply
執行以下操作後main.tf
,並等待實例通過檢查(然後再過一分鐘),嘗試 SSH 就會遇到困難。
$ ssh -v -i ~/.ssh/toydeploy.pem [email protected]
OpenSSH_7.6p1 Ubuntu-4ubuntu0.5, OpenSSL 1.0.2n 7 Dec 2017
debug1: Reading configuration data /etc/ssh/ssh_config
debug1: /etc/ssh/ssh_config line 19: Applying options for *
debug1: Connecting to 18.144.125.224 [18.144.125.224] port 22.
debug1: connect to address 18.144.125.224 port 22: Connection timed out
ssh: connect to host 18.144.125.224 port 22: Connection timed out
我已經使用相同的 AMI 和金鑰對手動啟動了一個實例,並且可以透過 SSH 登入。 DNS 名稱”對於手動部署的執行個體顯示“IPv4 (A)”,對於Terraformed 實例顯示“-”。兩者看起來都是良性的,但我可能是錯的。
terraform {
required_providers {
aws = {
source = "hashicorp/aws"
version = "~> 3.27"
}
}
}
provider "aws" {
profile = "default"
region = "us-west-1"
}
variable "cidr_vpc" {
description = "CIDR block for VPC"
default = "10.1.0.0/16"
}
variable "cidr_subnet" {
description = "CIDR block for subnet"
default = "10.1.0.0/20"
}
resource "aws_vpc" "toydeploy-vpc" {
cidr_block = var.cidr_vpc
enable_dns_hostnames = true
enable_dns_support = true
}
resource "aws_subnet" "toydeploy-subnet" {
vpc_id = aws_vpc.toydeploy-vpc.id
cidr_block = var.cidr_subnet
}
resource "aws_security_group" "toydeploy-sg" {
name = "toydeploy-sg"
vpc_id = aws_vpc.toydeploy-vpc.id
ingress {
from_port = 22
to_port = 22
protocol = "tcp"
cidr_blocks = [
"0.0.0.0/0"
]
}
# Terraform removes the default rule, so we re-add it.
egress {
from_port = 0
to_port = 0
protocol = "-1"
cidr_blocks = ["0.0.0.0/0"]
}
}
resource "aws_instance" "toydeploy" {
ami = "ami-083f68207d3376798" # Ubuntu 18.04
instance_type = "t2.micro"
security_groups = ["${aws_security_group.toydeploy-sg.id}"]
subnet_id = aws_subnet.toydeploy-subnet.id
associate_public_ip_address = true
key_name = "toydeploy"
}
如果下面沒有任何問題,並且您可以向我指出一個有效的範例,那麼我也將不勝感激。
解決
仔細檢查發現路由表只是子網路的路由,而不是 0.0.0.0/0。添加以下內容解決了該問題。
resource "aws_internet_gateway" "toydeploy-ig" {
vpc_id = aws_vpc.toydeploy-vpc.id
}
resource "aws_route_table" "toydeploy-rt" {
vpc_id = aws_vpc.toydeploy-vpc.id
route {
cidr_block = "0.0.0.0/0"
gateway_id = aws_internet_gateway.toydeploy-ig.id
}
}
resource "aws_route_table_association" "toydeploy-rta" {
subnet_id = aws_subnet.toydeploy-subnet.id
route_table_id = aws_route_table.toydeploy-rt.id
}
答案1
連線逾時通常表示網路問題。查看:
- 安全群組/NACL 在連接埠 22 上向您的 IP 開放
- VPC有網路網關
- 子網路有一條到網際網路閘道的路由
- 實例有公網IP
- 路由設定正確
這是您連接嘗試中的關鍵行,它告訴您發生了什麼
ssh: connect to host 18.144.125.224 port 22: Connection timed out