以下即為一個最基礎的網路架構,通常架構不會畫的這麼詳盡,大部分會省略security group
和route table
的部分。
可從圖中看出若一台ec2
需要上網,就必須將其所在的子網與路由表綁定,然後將路由指向internet gateway
。
示意圖
建置環境
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
|
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_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"
}
}
|
測試
從下圖可以看出我們可遠端連線ec2
且利用ec2
上網
後記
aws_route_table_association
aws_route_table_association
主要就是將subnet
與route table
綁定在一起的一項功能
map_public_ip_on_launch
map_public_ip_on_launch
主要功能是將子網中的instance賦予外網IP