Сеть Terraform EC2 сломана - PullRequest
1 голос
/ 20 июня 2020

Я использую Terraform 0.12.26 и хочу создать экземпляр AWS машины Ubuntu.

Когда я запускаю terraform apply, все выглядит правильно ... но я не могу sh к новой машине EC2. Мой домашний брандмауэр разрешает s sh везде, а я могу s sh для любых других rnet ресурсов.

Если я вручную устанавливаю экземпляр EC2 в том же регионе / az, s sh работает нормально ... эта проблема, похоже, ограничена Terraform.

$ terraform apply
...
Do you want to perform these actions?
  Terraform will perform the actions described above.
  Only 'yes' will be accepted to approve.

  Enter a value: yes

aws_key_pair.mykeypair: Creating...
aws_vpc.main: Creating...
aws_key_pair.mykeypair: Creation complete after 2s [id=mykeypair-pub]
aws_vpc.main: Still creating... [10s elapsed]
aws_vpc.main: Creation complete after 14s [id=vpc-0396212cf58236e68]
aws_subnet.first_subnet: Creating...
aws_security_group.ingress-policy-example: Creating...
aws_subnet.first_subnet: Creation complete after 10s [id=subnet-0558eb0d5c2a4cb3e]
aws_security_group.ingress-policy-example: Still creating... [10s elapsed]
aws_security_group.ingress-policy-example: Creation complete after 13s [id=sg-080e7fa96dc485107]
aws_instance.example: Creating...
aws_instance.example: Still creating... [10s elapsed]
aws_instance.example: Still creating... [20s elapsed]
aws_instance.example: Creation complete after 25s [id=i-0aaf3c53023c1226f]

Apply complete! Resources: 5 added, 0 changed, 0 destroyed.

Outputs:

ip = 34.217.88.173

$ telnet 34.217.88.173 22
Trying 34.217.88.173...
telnet: Unable to connect to remote host: Resource temporarily unavailable
$

aws_console_output

Это мой код terraform:

$ cat main.tf
provider "aws" {
  region     = var.region
  access_key = "SECRET_ACCESS_KEY_HERE"
  secret_key = "SECRET_KEY_HERE"

  # Allow any 2.x version of the AWS provider
  version = "~> 2.0"
}

variable region {
  default = "us-west-2"
}

variable availability_zone_01 {
  default = "us-west-2a"
}

variable key_path {
    default = "~/.ssh/id_rsa.pub"
}

variable site_supernet {
    default = "10.0.0.0/16"
}

variable first_subnet {
    default = "10.0.1.0/24"
}

resource "aws_vpc" "main" {
  cidr_block           = var.site_supernet
  enable_dns_hostnames = true
  enable_dns_support   = true
  instance_tenancy     = "default"

  tags = {
    Name = "tag-primary-vpc"
  }
}

resource "aws_subnet" "first_subnet" {
  vpc_id                  = aws_vpc.main.id
  cidr_block              = var.first_subnet
  availability_zone       = var.availability_zone_01
  map_public_ip_on_launch = true

  tags = {
    Name = "tag-first_subnet"
  }
}

resource "aws_security_group" "ingress-policy-example" {
  vpc_id        = aws_vpc.main.id
  ingress {
    cidr_blocks = ["0.0.0.0/0",]
    from_port   = 22  # Port from 22 to 22...
    to_port     = 22
    protocol    = "tcp"
  }

  ## This egress rule was missing from my original question...
  egress {
    # Terraform doesn't allow all egress traffic by default...
    cidr_blocks = ["0.0.0.0/0"]
    from_port   = 0
    to_port     = 0
    protocol    = "-1"
  }

  tags = {
    Name = "tag-sg-allow-ssh"
  }
}

resource "aws_key_pair" "mykeypair" {
  key_name   = "mykeypair-pub"
  public_key = file(var.key_path)
}

resource "aws_instance" "example" {
  #ami           = "ami-0994c095691a46fb5"
  ami           = "ami-003634241a8fcdec0"
  instance_type = "t2.nano"
  key_name      = aws_key_pair.mykeypair.key_name

  subnet_id                   = aws_subnet.first_subnet.id
  vpc_security_group_ids      = [
    aws_security_group.ingress-policy-example.id,
  ]
  associate_public_ip_address = true

  root_block_device {
    delete_on_termination = false
  }

  user_data = <<-EOF
              #!/bin/bash
              apt-get update
              apt-get install openssh-server
              EOF

  tags = {
    Name = "stackoverflow_20200619"
  }
}

output "ip" {
  value = aws_instance.example.public_ip
}

ВОПРОС : Как я могу исправить это развертывание terraform, чтобы я мог sh на сервере выше ?

ЧТО Я ПРОПЫТАЛ :

  • Создание образа Ubuntu вручную с помощью ключа auth; это работает нормально, и я могу s sh к нему
  • Удаление группы безопасности terraform; не помогает
  • Изменено AWS терраформирование регионов / зон доступности; не помогает
  • Удаление user_data установка пакета; не помогает
  • Удаление aws_subnet; не помогает
  • Удаление instance_tenancy; не помогает
  • Заменить ключ s sh на другой ключ s sh; не помогает
  • Замените ключ s sh на stati c логин / пароль; не помогает
  • S SH от Windows с PuTTY (вместо linux & открывает sh); не помогает

1 Ответ

6 голосов
/ 20 июня 2020

Ваш VP C не имеет шлюза Inte rnet (IGW). Вам нужно будет создать его и добавить для него запись в таблице маршрутов.

Добавление этих ресурсов должно сработать (написал это на моем телефоне, поэтому ваш пробег может отличаться):

resource "aws_internet_gateway" "igw" {
  vpc_id = aws_vpc.main.id

  tags = {
    Name = "main"
  }
}

resource "aws_route" "r" {
  route_table_id            = aws_route_table.rt
  destination_cidr_block    = "0.0.0.0/0"
  gateway_id = aws_internet_gateway.igw.id
}

resource "aws_route_table" "rt" {
  vpc_id = aws_vpc.main.id
}

resource "aws_route_table_association" "rta" {
  subnet_id      = aws_subnet.first_subnet.id
  route_table_id = aws_route_table.rt.id
}
...