我可以在 terraform 创建的 ec2 实例中执行 ssh 吗?

UTK*_*AVA 7 ssh amazon-ec2 ssh-keys terraform

我使用 terraform 创建了一个 ec2 实例(没有 .pem 密钥)。我可以在本地系统和 ec2 实例之间建立 ssh 连接吗?

jwi*_*ker 20

假设您使用v0.12.+具有以下结构的Terraform 配置了一个实例:

resource "aws_instance" "instance" {
  ami              = "${var.ami}"
  instance_type    = "t2.micro"
  count            = 1
  associate_public_ip_address = true
}
Run Code Online (Sandbox Code Playgroud)

您可以进行一些额外的设置:

  • 配置公网ip output
output "instance_ip" {
  description = "The public ip for ssh access"
  value       = aws_instance.instance.public_ip
}

Run Code Online (Sandbox Code Playgroud)
  • 创建一个aws_key_pair与现有的SSH公用密钥或创建一个新的 实例:
resource "aws_key_pair" "ssh-key" {
  key_name   = "ssh-key"
  public_key = "ssh-rsa AAAAB3Nza............"
}
Run Code Online (Sandbox Code Playgroud)
  • 像这样添加key_nameininstance资源:
resource "aws_instance" "instance" {
  ami              = var.ami
  instance_type    = "t2.micro"
  count            = 1
  associate_public_ip_address = true

  key_name         = "ssh-key"
}
Run Code Online (Sandbox Code Playgroud)
  • 现在您需要申请运行terraform applyterraform output返回公共IP

  • 获取您的公共 IP 并运行:

resource "aws_instance" "instance" {
  ami              = "${var.ami}"
  instance_type    = "t2.micro"
  count            = 1
  associate_public_ip_address = true
}
Run Code Online (Sandbox Code Playgroud)

或使用公钥路径

output "instance_ip" {
  description = "The public ip for ssh access"
  value       = aws_instance.instance.public_ip
}

Run Code Online (Sandbox Code Playgroud)

资料来源:

  • @ijt您需要验证端口 22 是否在安全组中打开,请检查:https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/authorizing-access-to-an-instance.html (2认同)