Featured image of post 透過Terraform在AWS上運行公私有網路

透過Terraform在AWS上運行公私有網路

Terraform AWS Public Private Network

以下為一個簡易的網路架構,主要強調公私有網路下的AWS環境,此一設計主要是讓私有網路路由不到網路,而公有網路能夠路由到外網,此一設計通常是為了保護不需要直接提供使用者直連的服務或裝置。

示意圖

建置環境

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
provider "aws" {
  region = "us-west-2"
}

resource "aws_vpc" "vpc" {
  cidr_block = "10.0.0.0/16"
  tags = {
    Name = "vpc"
  }
}

resource "aws_subnet" "subnet" {
  vpc_id                  = aws_vpc.vpc.id
  cidr_block              = "10.0.1.0/24"
  availability_zone       = "us-west-2a"
  map_public_ip_on_launch = true

  tags = {
    Name = "subnet"
  }
}

resource "aws_subnet" "subnet-private" {
  vpc_id                  = aws_vpc.vpc.id
  cidr_block              = "10.0.2.0/24"
  availability_zone       = "us-west-2a"

  tags = {
    Name = "subnet-private"
  }
}

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

resource "aws_route_table" "rt" {
  vpc_id = aws_vpc.vpc.id
  route {
    cidr_block = "0.0.0.0/0"
    gateway_id = aws_internet_gateway.igw.id
  }
  tags = {
    Name = "rt"
  }
}
resource "aws_internet_gateway" "igw" {
  vpc_id = aws_vpc.vpc.id

  tags = {
    Name = "igw"
  }
}

resource "aws_security_group" "sg" {
  name   = "sg"
  vpc_id = aws_vpc.vpc.id
  ingress {
    from_port   = 22
    to_port     = 22
    protocol    = "tcp"
    cidr_blocks = ["0.0.0.0/0"]
  }
  egress {
    from_port   = 0
    to_port     = 0
    protocol    = "-1"
    cidr_blocks = ["0.0.0.0/0"]
  }
  tags = {
    Name = "sg"
  }
}

resource "aws_instance" "ec2" {
  ami                    = "ami-0747e613a2a1ff483"
  instance_type          = "t2.micro"
  key_name               = "demo-key-us-west-2"
  subnet_id              = aws_subnet.subnet.id
  vpc_security_group_ids = [aws_security_group.sg.id]
  tags = {
    Name = "ec2"
  }
}

resource "aws_instance" "ec2-private" {
  ami                    = "ami-0747e613a2a1ff483"
  instance_type          = "t2.micro"
  key_name               = "demo-key-us-west-2"
  subnet_id              = aws_subnet.subnet-private.id
  vpc_security_group_ids = [aws_security_group.sg.id]
  tags = {
    Name = "ec2-private"
  }
}

測試

public subnet中的ec2可正常連網

利用預設路由(也就是vpc被建立時就被建立的路由)來透過public subnet中的ec2連線在private subnet中的ec2

private subnet中的ec2無法正常連網

後記 : 上傳key到ec2

由於public subnet中的ec2沒有key,這樣會無法ssh到private subnet中的ec2,因此可以透過scp將key上傳。

1
scp -i ./demo-key-us-west-2.pem ./demo-key-us-west-2.pem ec2-user@34.221.228.11:/home/ec2-user/tmp.pem
comments powered by Disqus
Built with Hugo
Theme Stack designed by Jimmy