-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.tf
More file actions
410 lines (363 loc) · 10.8 KB
/
Copy pathmain.tf
File metadata and controls
410 lines (363 loc) · 10.8 KB
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
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
locals {
name = var.name
lifecycle_hook_name = "${local.name}-hook"
default_egress_rules = {
egress_http = {
cidr_ipv4 = "0.0.0.0/0"
description = "Allow outbound HTTP traffic."
ip_protocol = "tcp"
from_port = 80
to_port = 80
},
egress_https = {
cidr_ipv4 = "0.0.0.0/0"
description = "Allow outbound HTTPS traffic."
ip_protocol = "tcp"
from_port = 443
to_port = 443
},
}
default_ingress_rules = { for key, value in data.aws_subnet.private :
"ingress-${value.id}" => {
cidr_ipv4 = value.cidr_block
description = "Allow inbound traffic from private subnet ${value.id}."
ip_protocol = "-1"
from_port = -1
to_port = -1
}
}
userdata = templatefile("${path.module}/templates/cloud-init.tpl", {
architecture = local.architecture
aws_region = data.aws_region.current.region
eip_allocation_id = var.enable_eip ? aws_eip.nat[0].id : ""
lifecycle_hook_name = local.lifecycle_hook_name
s3_bucket = module.config_bucket.s3_bucket_id
vpc_cidr_block = data.aws_vpc.this.cidr_block
})
}
resource "aws_cloudwatch_log_group" "access" {
name = "/nat-instance/access.log"
retention_in_days = 14
}
resource "aws_cloudwatch_log_group" "cache" {
name = "/nat-instance/cache.log"
retention_in_days = 14
}
resource "aws_cloudwatch_log_group" "iptables" {
name = "/nat-instance/iptables.log"
retention_in_days = 14
}
resource "aws_security_group" "instance" {
name = "${local.name}-instance-sg"
description = "Security group for NAT instance/squid proxy instances."
vpc_id = data.aws_vpc.this.id
tags = {
Name = "${local.name}-instance-sg"
}
lifecycle {
create_before_destroy = true
}
}
resource "aws_vpc_security_group_egress_rule" "this" {
for_each = merge(local.default_egress_rules, var.additional_egress_rules)
cidr_ipv4 = try(each.value.cidr_ipv4, null)
cidr_ipv6 = try(each.value.cidr_ipv6, null)
description = try(each.value.description, null)
from_port = try(each.value.from_port, null)
ip_protocol = each.value.ip_protocol
prefix_list_id = try(each.value.prefix_list_id, null)
referenced_security_group_id = try(each.value.referenced_security_group_id, null)
security_group_id = aws_security_group.instance.id
tags = merge(
var.tags,
{ "Name" = coalesce(try(each.value.name, null), "${aws_security_group.instance.name}-${each.key}") },
)
to_port = try(coalesce(each.value.to_port, each.value.from_port), null)
}
resource "aws_vpc_security_group_ingress_rule" "this" {
for_each = merge(local.default_ingress_rules, var.additional_ingress_rules)
cidr_ipv4 = try(each.value.cidr_ipv4, null)
cidr_ipv6 = try(each.value.cidr_ipv6, null)
description = try(each.value.description, null)
from_port = try(each.value.from_port, null)
ip_protocol = each.value.ip_protocol
prefix_list_id = try(each.value.prefix_list_id, null)
referenced_security_group_id = try(each.value.referenced_security_group_id, null)
security_group_id = aws_security_group.instance.id
tags = merge(
var.tags,
{ "Name" = coalesce(try(each.value.name, null), "${aws_security_group.instance.name}-${each.key}") },
)
to_port = try(coalesce(each.value.to_port, each.value.from_port), null)
}
resource "aws_iam_role" "instance" {
name = "${local.name}-instance-role"
assume_role_policy = jsonencode({
Version = "2012-10-17"
Statement = [
{
Action = "sts:AssumeRole"
Effect = "Allow"
Principal = {
Service = "ec2.amazonaws.com"
}
},
]
})
}
# Custom IAM policy for the NAT instance/squid instance
resource "aws_iam_policy" "instance" {
name = "${local.name}-instance-policy"
description = "Policy for the NAT instance/squid proxy instances."
policy = data.aws_iam_policy_document.instance.json
}
data "aws_iam_policy_document" "instance" {
statement {
sid = "ssm"
actions = [
"ssm:UpdateInstanceInformation",
"ssmmessages:CreateControlChannel",
"ssmmessages:CreateDataChannel",
"ssmmessages:OpenControlChannel",
"ssmmessages:OpenDataChannel",
]
resources = ["*"]
}
statement {
sid = "ec2messages"
actions = [
"ec2messages:AcknowledgeMessage",
"ec2messages:DeleteMessage",
"ec2messages:FailMessage",
"ec2messages:GetEndpoint",
"ec2messages:GetMessages",
"ec2messages:SendReply",
]
resources = ["*"]
}
statement {
sid = "EC2"
actions = [
"ec2:DescribeInstances",
"ec2:ModifyInstanceAttribute",
]
resources = [
"arn:aws:ec2:${data.aws_region.current.region}:${data.aws_caller_identity.this.account_id}:instance/*"
]
}
dynamic "statement" {
for_each = var.enable_eip ? ["true"] : []
content {
sid = "DescribeEIP"
actions = [
"ec2:AssociateAddress",
"ec2:DescribeAddresses",
]
resources = [
"arn:aws:ec2:${data.aws_region.current.region}:${data.aws_caller_identity.this.account_id}:elastic-ip/*",
"arn:aws:ec2:${data.aws_region.current.region}:${data.aws_caller_identity.this.account_id}:network-interface/*",
]
}
}
statement {
sid = "AsgLifecycle"
actions = [
"autoscaling:CompleteLifecycleAction",
]
resources = [
join(":", [
"arn:aws:autoscaling",
data.aws_region.current.region,
data.aws_caller_identity.this.account_id,
"autoScalingGroup:*:autoScalingGroupName/${local.name}-asg",
]),
]
}
statement {
sid = "S3"
actions = [
"s3:ListBucket",
"s3:GetObject",
"s3:ListObject",
]
resources = [
module.config_bucket.s3_bucket_arn,
"${module.config_bucket.s3_bucket_arn}*"
]
}
}
# Attach the custom policy to the role
resource "aws_iam_role_policy_attachment" "custom" {
role = aws_iam_role.instance.name
policy_arn = aws_iam_policy.instance.arn
}
resource "aws_iam_role_policy_attachment" "cloudwatch" {
role = aws_iam_role.instance.name
policy_arn = "arn:aws:iam::aws:policy/CloudWatchAgentServerPolicy"
}
resource "aws_iam_instance_profile" "instance" {
name = "${local.name}-instance-profile"
role = aws_iam_role.instance.name
}
resource "aws_launch_template" "nat" {
name = "${local.name}-launchtemplate"
image_id = data.aws_ami.amazon_linux_2.id
instance_type = var.instance_type
block_device_mappings {
device_name = "/dev/xvda"
ebs {
volume_size = 8
volume_type = "gp3"
encrypted = "true"
}
}
iam_instance_profile {
name = aws_iam_instance_profile.instance.name
}
metadata_options {
http_endpoint = "enabled"
http_tokens = "required"
http_put_response_hop_limit = 1
instance_metadata_tags = "enabled"
}
monitoring {
enabled = var.detailed_monitoring
}
network_interfaces {
associate_public_ip_address = true
delete_on_termination = true
security_groups = [
aws_security_group.instance.id,
]
}
user_data = base64encode(local.userdata)
tag_specifications {
resource_type = "instance"
tags = merge({
UserDataHash = md5(local.userdata)
}, var.tags)
}
tag_specifications {
resource_type = "volume"
tags = merge({
Name = "${local.name}-volume"
}, var.tags)
}
}
resource "aws_eip" "nat" {
count = var.enable_eip ? 1 : 0
tags = {
Name = "${local.name}-eip"
}
}
resource "aws_autoscaling_group" "nat" {
name = "${local.name}-asg"
max_size = 1
min_size = 1
health_check_grace_period = 300
health_check_type = "EC2"
default_instance_warmup = 30
vpc_zone_identifier = var.public_subnet_ids
initial_lifecycle_hook {
name = local.lifecycle_hook_name
lifecycle_transition = "autoscaling:EC2_INSTANCE_LAUNCHING"
heartbeat_timeout = 300
default_result = "ABANDON"
notification_target_arn = aws_sns_topic.asg_lifecycle.arn
role_arn = aws_iam_role.asg_lifecycle.arn
}
instance_maintenance_policy {
max_healthy_percentage = 200
min_healthy_percentage = 100
}
instance_refresh {
strategy = "Rolling"
preferences {
min_healthy_percentage = 100
}
}
mixed_instances_policy {
instances_distribution {
on_demand_base_capacity = var.enable_spot_instance ? 0 : 1
on_demand_percentage_above_base_capacity = 0
}
launch_template {
launch_template_specification {
launch_template_id = aws_launch_template.nat.id
version = aws_launch_template.nat.latest_version
}
}
}
tag {
key = "Name"
propagate_at_launch = true
value = "${local.name}-instance"
}
tag {
key = "RouteTableIds"
propagate_at_launch = false
value = join(",", distinct(data.aws_route_table.private[*].id))
}
dynamic "tag" {
for_each = var.tags
content {
key = tag.key
propagate_at_launch = false
value = tag.value
}
}
depends_on = [
module.squid_config,
module.whitelist,
aws_cloudwatch_log_group.access,
aws_cloudwatch_log_group.cache,
aws_cloudwatch_log_group.iptables,
aws_eip.nat,
aws_lambda_function.nat,
aws_iam_role_policy_attachment.cloudwatch,
aws_iam_role_policy_attachment.custom,
aws_iam_role_policy.asg_lifecycle,
]
}
# IAM role for ASG lifecycle hook
resource "aws_iam_role" "asg_lifecycle" {
name = "${local.name}-asg-lifecycle-role"
assume_role_policy = jsonencode({
Version = "2012-10-17"
Statement = [
{
Effect = "Allow"
Principal = {
Service = "autoscaling.amazonaws.com"
}
Action = "sts:AssumeRole"
}
]
})
}
resource "aws_iam_role_policy" "asg_lifecycle" {
name = "${local.name}-asg-lifecycle-policy"
role = aws_iam_role.asg_lifecycle.id
policy = jsonencode({
Version = "2012-10-17"
Statement = [
{
Effect = "Allow"
Action = [
"sns:Publish"
]
Resource = aws_sns_topic.asg_lifecycle.arn
}
]
})
}
# SNS topic for lifecycle hook
resource "aws_sns_topic" "asg_lifecycle" {
name = "${local.name}-asg-lifecycle-topic"
kms_master_key_id = "alias/aws/sns"
}
resource "aws_sns_topic_subscription" "lambda_sub" {
topic_arn = aws_sns_topic.asg_lifecycle.arn
protocol = "lambda"
endpoint = aws_lambda_function.nat.arn
}