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
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
| #!/usr/bin/env python
# main.py
from constructs import Construct
from cdktf import App, TerraformStack, TerraformOutput
from cdktf_cdktf_provider_aws.provider import AwsProvider
from cdktf_cdktf_provider_aws.vpc import Vpc
from cdktf_cdktf_provider_aws.subnet import Subnet
from cdktf_cdktf_provider_aws.internet_gateway import InternetGateway
from cdktf_cdktf_provider_aws.route_table import RouteTable, RouteTableRoute
from cdktf_cdktf_provider_aws.route_table_association import RouteTableAssociation
from cdktf_cdktf_provider_aws.security_group import SecurityGroup, SecurityGroupIngress, SecurityGroupEgress
from cdktf_cdktf_provider_aws.instance import Instance
from dataclasses import dataclass
from typing import List, Optional
@dataclass
class EnvironmentConfig:
"""環境配置類別"""
name: str
region: str
vpc_cidr: str
subnet_cidrs: List[str]
instance_type: str = "t3.micro"
class NetworkConstruct(Construct):
"""網路基礎架構 Construct"""
def __init__(
self,
scope: Construct,
id: str,
vpc_cidr: str,
subnet_cidrs: List[str],
region: str,
environment: str,
):
super().__init__(scope, id)
# VPC
self.vpc = Vpc(
self,
"vpc",
cidr_block=vpc_cidr,
enable_dns_hostnames=True,
enable_dns_support=True,
tags={"Name": f"{environment}-vpc", "Environment": environment},
)
# Internet Gateway
self.igw = InternetGateway(
self,
"igw",
vpc_id=self.vpc.id,
tags={"Name": f"{environment}-igw"},
)
# Public Subnets
self.public_subnets = []
availability_zones = ["a", "b", "c"]
for i, cidr in enumerate(subnet_cidrs):
az = f"{region}{availability_zones[i % len(availability_zones)]}"
subnet = Subnet(
self,
f"public_subnet_{i}",
vpc_id=self.vpc.id,
cidr_block=cidr,
availability_zone=az,
map_public_ip_on_launch=True,
tags={
"Name": f"{environment}-public-subnet-{az}",
"Environment": environment,
},
)
self.public_subnets.append(subnet)
# Route Table
self.public_route_table = RouteTable(
self,
"public_rt",
vpc_id=self.vpc.id,
route=[
RouteTableRoute(
cidr_block="0.0.0.0/0",
gateway_id=self.igw.id,
)
],
tags={"Name": f"{environment}-public-rt"},
)
# Route Table Associations
for i, subnet in enumerate(self.public_subnets):
RouteTableAssociation(
self,
f"public_rta_{i}",
subnet_id=subnet.id,
route_table_id=self.public_route_table.id,
)
class WebServerConstruct(Construct):
"""Web 伺服器 Construct"""
def __init__(
self,
scope: Construct,
id: str,
vpc_id: str,
subnet_id: str,
instance_type: str,
environment: str,
allowed_ssh_cidrs: Optional[List[str]] = None,
):
super().__init__(scope, id)
allowed_ssh_cidrs = allowed_ssh_cidrs or ["0.0.0.0/0"]
# Security Group
self.security_group = SecurityGroup(
self,
"sg",
name=f"{environment}-web-sg",
description="Security group for web servers",
vpc_id=vpc_id,
ingress=[
SecurityGroupIngress(
description="HTTP",
from_port=80,
to_port=80,
protocol="tcp",
cidr_blocks=["0.0.0.0/0"],
),
SecurityGroupIngress(
description="HTTPS",
from_port=443,
to_port=443,
protocol="tcp",
cidr_blocks=["0.0.0.0/0"],
),
SecurityGroupIngress(
description="SSH",
from_port=22,
to_port=22,
protocol="tcp",
cidr_blocks=allowed_ssh_cidrs,
),
],
egress=[
SecurityGroupEgress(
from_port=0,
to_port=0,
protocol="-1",
cidr_blocks=["0.0.0.0/0"],
)
],
tags={"Name": f"{environment}-web-sg"},
)
# User Data Script
user_data = """#!/bin/bash
yum update -y
yum install -y httpd
systemctl start httpd
systemctl enable httpd
echo "<h1>Hello from CDKTF Python!</h1>" > /var/www/html/index.html
"""
# EC2 Instance
self.instance = Instance(
self,
"instance",
ami="ami-0c55b159cbfafe1f0",
instance_type=instance_type,
subnet_id=subnet_id,
vpc_security_group_ids=[self.security_group.id],
associate_public_ip_address=True,
user_data=user_data,
tags={
"Name": f"{environment}-web-server",
"Environment": environment,
},
)
class WebInfrastructureStack(TerraformStack):
"""完整的 Web 基礎架構 Stack"""
def __init__(self, scope: Construct, id: str, config: EnvironmentConfig):
super().__init__(scope, id)
# AWS Provider
AwsProvider(self, "AWS", region=config.region)
# Network Layer
network = NetworkConstruct(
self,
"network",
vpc_cidr=config.vpc_cidr,
subnet_cidrs=config.subnet_cidrs,
region=config.region,
environment=config.name,
)
# Web Server Layer
web_server = WebServerConstruct(
self,
"web",
vpc_id=network.vpc.id,
subnet_id=network.public_subnets[0].id,
instance_type=config.instance_type,
environment=config.name,
)
# Outputs
TerraformOutput(
self,
"vpc_id",
value=network.vpc.id,
description="VPC ID",
)
TerraformOutput(
self,
"web_server_public_ip",
value=web_server.instance.public_ip,
description="Web server public IP address",
)
TerraformOutput(
self,
"web_server_public_dns",
value=web_server.instance.public_dns,
description="Web server public DNS name",
)
# 主程式
app = App()
# 開發環境配置
dev_config = EnvironmentConfig(
name="dev",
region="ap-northeast-1",
vpc_cidr="10.0.0.0/16",
subnet_cidrs=["10.0.1.0/24", "10.0.2.0/24"],
instance_type="t3.micro",
)
# 生產環境配置
prod_config = EnvironmentConfig(
name="prod",
region="ap-northeast-1",
vpc_cidr="10.1.0.0/16",
subnet_cidrs=["10.1.1.0/24", "10.1.2.0/24", "10.1.3.0/24"],
instance_type="t3.small",
)
# 建立 Stacks
WebInfrastructureStack(app, "dev-infrastructure", dev_config)
WebInfrastructureStack(app, "prod-infrastructure", prod_config)
app.synth()
|