无法通过 SSH 连接到使用 Terraform 创建的 EC2 实例



我正在做一个非常简单的Terraform项目。我正在使用窗口命令提示符。我现在只有一个 EC2 实例。这是项目结构 -

terraform-project
|_ec2.tf
|_vars.tf
|_test-key
|_test-key.pub
|_.terraform
|_terraform.tfstate

ec2.tf 文件如下 -

provider "aws" {
region = "eu-central-1"
}
resource "aws_key_pair" "test-key"{
key_name = "test-key"
public_key = "${file("test-key.pub")}"
}
resource "aws_instance" "my-ec2"{
ami = "${var.ami}"
instance_type = "${var.instance_type}"
key_name = "${aws_key_pair.test-key.key_name}"
tags = {
Name = "Terraform"
Batch = "7am"
}
}

vars.tf 文件如下 -

variable "ami" {
default = "ami-0233214e13e500f77"
}
variable "instance_type" {
default = "t2.micro"
}

Terraform App成功运行,我可以从AWS管理控制台看到该实例。但是当我尝试通过SSH连接到实例时,我遇到了权限问题-

ssh -i test-key ec2-user@54.xx.xxx.xxx
ssh: connect to host 54.xx.xxx.xxx port 22: Permission denied

实例具有默认的 VPC 和安全组。允许所有入站和出站流量。 我在公司代理后面工作。在我开始之前,我在 windows 命令提示符上设置了代理设置 -

set HTTP_PROXY=http://proxy.companytnet.net:port
set HTTPS_PROXY=http://proxy.companynet.net:port

带有详细内容的 SSH 给出了这个:

ssh -vvv -i test-key ec2-user@54.xx.xxx.xxx
OpenSSH_for_Windows_7.7p1, LibreSSL 2.6.5
debug1: Reading configuration data C:\Users\M710583/.ssh/config
debug3: Failed to open file:C:/ProgramData/ssh/ssh_config error:2
debug2: resolve_canonicalize: hostname 54.xx.xxx.xxx is address
debug2: ssh_connect_direct: needpriv 0
debug1: Connecting to 54.xx.xxx.xxx [54.xx.xxx.xxx] port 22.
debug3: finish_connect - ERROR: async io completed with error: 10013, io:00000256B95289B0
debug1: connect to address 54.xx.xxx.xxx port 22: Permission denied
ssh: connect to host 54.xx.xxx.xxx port 22: Permission denied

我可以通过SSH连接到其他服务器和实例,但不能连接到使用Terraform创建的服务器和实例。我做错了什么?

您需要添加适当的安全组。像这样:

resource "aws_security_group" "main" {
egress = [
{
cidr_blocks      = [ "0.0.0.0/0", ]
description      = ""
from_port        = 0
ipv6_cidr_blocks = []
prefix_list_ids  = []
protocol         = "-1"
security_groups  = []
self             = false
to_port          = 0
}
]
ingress                = [
{
cidr_blocks      = [ "0.0.0.0/0", ]
description      = ""
from_port        = 22
ipv6_cidr_blocks = []
prefix_list_ids  = []
protocol         = "tcp"
security_groups  = []
self             = false
to_port          = 22
}
]
}

resource "aws_instance" "my-ec2"{
ami = "${var.ami}"
instance_type = "${var.instance_type}"
key_name = "${aws_key_pair.test-key.key_name}"
tags = {
Name = "Terraform"
Batch = "7am"
}
vpc_security_group_ids = [aws_security_group.main.id]
}

我建议将vpc_security_group_ids = "${aws_security_group.main-sg.id}"添加到您的EC2资源块中。

此属性将您的 VPC 与您引用的安全组相关联;在此处阅读有关它的更多信息。

相关内容

  • 没有找到相关文章

最新更新