-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.tf
388 lines (328 loc) · 14.2 KB
/
main.tf
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
#------------------------------------------------------------------------------
# EC2
#------------------------------------------------------------------------------
resource "aws_instance" "this" {
ami = data.aws_ami.this.id
associate_public_ip_address = false # create an EIP instead
disable_api_termination = var.instance.disable_api_termination
disable_api_stop = var.instance.disable_api_stop
ebs_optimized = data.aws_ec2_instance_type.this.ebs_optimized_support == "unsupported" ? false : true
iam_instance_profile = aws_iam_instance_profile.this.name
instance_type = var.instance.instance_type
key_name = var.instance.key_name
monitoring = coalesce(var.instance.monitoring, true)
subnet_id = var.subnet_id
user_data = length(data.cloudinit_config.this) == 0 ? var.user_data_raw : data.cloudinit_config.this[0].rendered
vpc_security_group_ids = var.instance.vpc_security_group_ids
metadata_options {
#checkov:skip=CKV_AWS_79:This isn't enabled in every environment, so we can't enforce it
http_endpoint = coalesce(var.instance.metadata_endpoint_enabled, "enabled")
http_tokens = coalesce(var.instance.metadata_options_http_tokens, "required") #tfsec:ignore:aws-ec2-enforce-http-token-imds
}
root_block_device {
delete_on_termination = true
encrypted = true
iops = try(local.ebs_volume_root.iops > 0, false) ? local.ebs_volume_root.iops : null
kms_key_id = try(local.ebs_volume_root.kms_key_id, var.ebs_kms_key_id)
throughput = try(local.ebs_volume_root.throughput > 0, false) ? local.ebs_volume_root.throughput : null
volume_size = local.ebs_volume_root.size
volume_type = local.ebs_volume_root.type
tags = merge(local.tags, var.ebs_volume_tags, {
Name = join("-", [var.name, "root", data.aws_ami.this.root_device_name])
})
}
# block devices specified inline cannot be resized later so remove them here
# and define as ebs_volumes later
dynamic "ephemeral_block_device" {
for_each = try(var.instance.ebs_block_device_inline, false) ? {} : local.ami_block_device_mappings_nonroot
content {
device_name = ephemeral_block_device.value.device_name
no_device = true
}
}
# only use this inline EBS block if it is easy to recreate the EBS volume
# as the block is only used when the EC2 is first created
dynamic "ebs_block_device" {
for_each = try(var.instance.ebs_block_device_inline, false) ? local.ebs_volumes_nonroot : {}
content {
device_name = ebs_block_device.key
delete_on_termination = true
encrypted = true
iops = try(ebs_block_device.value.iops > 0, false) ? ebs_block_device.value.iops : null
kms_key_id = try(ebs_block_device.value.kms_key_id, var.ebs_kms_key_id)
throughput = try(ebs_block_device.value.throughput > 0, false) ? ebs_block_device.value.throughput : null
volume_size = ebs_block_device.value.size
volume_type = ebs_block_device.value.type
tags = merge(local.tags, var.ebs_volume_tags, {
Name = try(
join("-", [var.name, ebs_block_device.value.label, ebs_block_device.key]),
join("-", [var.name, ebs_block_device.key])
)
})
}
}
dynamic "private_dns_name_options" {
for_each = var.instance.private_dns_name_options != null ? [var.instance.private_dns_name_options] : []
content {
enable_resource_name_dns_aaaa_record = private_dns_name_options.value.enable_resource_name_dns_aaaa_record
enable_resource_name_dns_a_record = private_dns_name_options.value.enable_resource_name_dns_a_record
hostname_type = private_dns_name_options.value.hostname_type
}
}
lifecycle {
ignore_changes = [
user_data, # Prevent changes to user_data from destroying existing EC2s
ebs_block_device, # Otherwise EC2 will be refreshed each time
associate_public_ip_address # The state erroneously has this set to true after an EC2 is restarted with EIP attached
]
}
tags = merge(local.tags, var.instance.tags, {
Name = var.name
})
}
#------------------------------------------------------------------------------
# PUBLIC IP
#------------------------------------------------------------------------------
resource "aws_eip" "this" {
#checkov:skip=CKV2_AWS_19: "EIP attachment is handled through separate resource"
count = var.instance.associate_public_ip_address ? 1 : 0
domain = "vpc"
tags = merge(local.tags, {
Name = var.name
})
}
resource "aws_eip_association" "this" {
count = var.instance.associate_public_ip_address ? 1 : 0
instance_id = aws_instance.this.id
allocation_id = aws_eip.this[0].id
}
#------------------------------------------------------------------------------
# DISKS
#------------------------------------------------------------------------------
resource "aws_ebs_volume" "this" {
#tfsec:ignore:aws-ebs-encryption-customer-key:exp:2022-10-31: I don't think we need the fine grained control CMK would provide
#checkov:skip=CKV_AWS_189:I don't think we need the fine grained control CMK would provide
for_each = try(var.instance.ebs_block_device_inline, false) ? {} : local.ebs_volumes_nonroot
availability_zone = var.availability_zone
encrypted = true
kms_key_id = try(each.value.kms_key_id, var.ebs_kms_key_id)
iops = try(each.value.iops > 0, false) ? each.value.iops : null
throughput = try(each.value.throughput > 0, false) ? each.value.throughput : null
size = each.value.size
type = lookup(each.value, "type", null)
# you may run into a permission issue if the AMI is not in self account
snapshot_id = lookup(each.value, "snapshot_id", null)
tags = merge(local.tags, var.ebs_volume_tags, {
Name = try(
join("-", [var.name, each.value.label, each.key]),
join("-", [var.name, each.key])
)
})
lifecycle {
ignore_changes = [snapshot_id] # retain data if AMI is updated. If you want to start from fresh, destroy it
}
}
resource "aws_volume_attachment" "this" {
for_each = aws_ebs_volume.this
device_name = each.key
volume_id = each.value.id
instance_id = aws_instance.this.id
}
#------------------------------------------------------------------------------
# Route 53 record
#------------------------------------------------------------------------------
resource "aws_route53_record" "internal" {
count = var.route53_records.create_internal_record ? 1 : 0
provider = aws.core-vpc
zone_id = data.aws_route53_zone.internal.zone_id
name = "${var.name}.${var.application_name}.${data.aws_route53_zone.internal.name}"
type = "A"
ttl = 60
records = [aws_instance.this.private_ip]
}
resource "aws_route53_record" "external" {
count = var.route53_records.create_external_record ? 1 : 0
provider = aws.core-vpc
zone_id = data.aws_route53_zone.external.zone_id
name = "${var.name}.${var.application_name}.${data.aws_route53_zone.external.name}"
type = "A"
ttl = 60
records = [var.instance.associate_public_ip_address ? aws_eip.this[0].public_ip : aws_instance.this.private_ip]
}
#------------------------------------------------------------------------------
# SSM Parameters
#------------------------------------------------------------------------------
resource "random_password" "this" {
for_each = local.ssm_random_passwords
length = each.value.length
special = each.value.special
}
# SSM parameters with values managed by terraform
resource "aws_ssm_parameter" "this" {
#checkov:skip=CKV2_AWS_34: AWS SSM Parameter should be Encrypted. SecureString is the default but can be changed by user if needed
for_each = merge(
local.ssm_parameters_value,
local.ssm_parameters_random,
)
name = "/${var.ssm_parameters_prefix}${var.name}/${each.key}"
description = each.value.description
type = each.value.type
key_id = each.value.kms_key_id
value = each.value.value
tags = merge(local.tags, {
Name = "${var.name}-${each.key}"
})
}
# Placeholder SSM parameters with values set elsewhere
resource "aws_ssm_parameter" "placeholder" {
#checkov:skip=CKV2_AWS_34: AWS SSM Parameter should be Encrypted. SecureString is the default but can be changed by user if needed
for_each = local.ssm_parameters_default
name = "/${var.ssm_parameters_prefix}${var.name}/${each.key}"
description = each.value.description
type = each.value.type
key_id = each.value.kms_key_id
value = each.value.value
tags = merge(local.tags, {
Name = "${var.name}-${each.key}"
})
lifecycle {
ignore_changes = [value]
}
}
#------------------------------------------------------------------------------
# SecretManager Secrets
#------------------------------------------------------------------------------
resource "random_password" "secrets" {
for_each = local.secretsmanager_random_passwords
length = each.value.length
special = each.value.special
}
resource "aws_secretsmanager_secret" "fixed" {
# skipped check as the secret value is defined by terraform so cannot be rotated by AWS
#checkov:skip=CKV2_AWS_57: Ensure Secrets Manager secrets should have automatic rotation enabled
for_each = merge(
local.secretsmanager_secrets_value,
local.secretsmanager_secrets_random,
)
name = "/${var.secretsmanager_secrets_prefix}${var.name}/${each.key}"
description = each.value.description
kms_key_id = each.value.kms_key_id
recovery_window_in_days = each.value.recovery_window_in_days
tags = merge(local.tags, {
Name = "${var.name}-${each.key}"
})
}
resource "aws_secretsmanager_secret_version" "fixed" {
for_each = merge(
local.secretsmanager_secrets_value,
local.secretsmanager_secrets_random,
)
secret_id = aws_secretsmanager_secret.fixed[each.key].id
secret_string = each.value.value
}
resource "aws_secretsmanager_secret" "placeholder" {
# Rotation can be added later as a configurable option
#checkov:skip=CKV2_AWS_57: Ensure Secrets Manager secrets should have automatic rotation enabled
for_each = local.secretsmanager_secrets_default
name = "/${var.secretsmanager_secrets_prefix}${var.name}/${each.key}"
description = each.value.description
kms_key_id = each.value.kms_key_id
recovery_window_in_days = each.value.recovery_window_in_days
tags = merge(local.tags, {
Name = "${var.name}-${each.key}"
})
}
#------------------------------------------------------------------------------
# Instance IAM role extra permissions
# Allow GetParameter to the EC2 scoped SSM parameter path
# Allow PutParameter to the EC2 scoped SSM parameter path if there are
# placeholder SSM parameters (e.g. parameters generated elsewhere in the
# provisioning process such as ansible)
#------------------------------------------------------------------------------
data "aws_iam_policy_document" "ssm_params_and_secrets" {
count = var.ssm_parameters != null || var.secretsmanager_secrets != null ? 1 : 0
dynamic "statement" {
for_each = var.ssm_parameters != null ? ["ssm"] : []
content {
effect = "Allow"
actions = flatten([
"ssm:GetParameter",
length(aws_ssm_parameter.placeholder) != 0 ? ["ssm:PutParameter"] : []
])
#tfsec:ignore:aws-iam-no-policy-wildcards: acccess scoped to parameter path of EC2
resources = ["arn:aws:ssm:${var.region}:${data.aws_caller_identity.current.id}:parameter/${var.ssm_parameters_prefix}${var.name}/*"]
}
}
dynamic "statement" {
for_each = var.secretsmanager_secrets != null ? ["secret"] : []
content {
effect = "Allow"
actions = flatten([
"secretsmanager:GetSecretValue",
length(aws_secretsmanager_secret.placeholder) != 0 ? ["secretsmanager:PutSecretValue"] : []
])
#tfsec:ignore:aws-iam-no-policy-wildcards: acccess scoped to parameter path of EC2
resources = ["arn:aws:secretsmanager:${var.region}:${data.aws_caller_identity.current.id}:secret:/${var.secretsmanager_secrets_prefix}${var.name}/*"]
}
}
}
resource "aws_iam_role" "this" {
name = "${var.iam_resource_names_prefix}-role-${var.name}"
path = "/"
max_session_duration = "3600"
assume_role_policy = jsonencode(
{
"Version" : "2012-10-17",
"Statement" : [
{
"Effect" : "Allow",
"Principal" : {
"Service" : "ec2.amazonaws.com"
}
"Action" : "sts:AssumeRole",
"Condition" : {}
}
]
}
)
managed_policy_arns = concat(["arn:aws:iam::aws:policy/AmazonSSMManagedInstanceCore"], var.instance_profile_policies)
tags = merge(
local.tags,
{
Name = "${var.iam_resource_names_prefix}-role-${var.name}"
},
)
}
resource "aws_iam_role_policy" "ssm_params_and_secrets" {
count = length(data.aws_iam_policy_document.ssm_params_and_secrets)
name = "Ec2SSMParamsAndSecretsPolicy-${var.name}"
role = aws_iam_role.this.id
policy = data.aws_iam_policy_document.ssm_params_and_secrets[count.index].json
}
resource "aws_iam_instance_profile" "this" {
name = "${var.iam_resource_names_prefix}-profile-${var.name}"
role = aws_iam_role.this.name
path = "/"
}
resource "aws_cloudwatch_metric_alarm" "this" {
for_each = var.cloudwatch_metric_alarms
alarm_name = "${var.name}-${each.key}"
comparison_operator = each.value.comparison_operator
evaluation_periods = each.value.evaluation_periods
metric_name = each.value.metric_name
namespace = each.value.namespace
period = each.value.period
statistic = each.value.statistic
threshold = each.value.threshold
alarm_actions = each.value.alarm_actions
ok_actions = each.value.ok_actions
alarm_description = each.value.alarm_description
datapoints_to_alarm = each.value.datapoints_to_alarm
treat_missing_data = each.value.treat_missing_data
dimensions = merge(each.value.dimensions, {
"InstanceId" = aws_instance.this.id
})
tags = merge(local.tags, {
Name = "${var.name}-${each.key}"
})
}