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
|
# EBS volumes ================================================================
resource "aws_ebs_volume" "this" {
for_each = var.volumes
availability_zone = each.value.availability_zone
size = each.value.size
type = each.value.type
iops = each.value.iops
throughput = each.value.throughput
encrypted = each.value.encrypted
kms_key_id = each.value.kms_key_id
multi_attach_enabled = each.value.multi_attach_enabled
snapshot_id = each.value.snapshot_id
final_snapshot = each.value.final_snapshot
tags = merge(local.tags, { Name = each.key })
}
# Volume attachments ---------------------------------------------------------
data "aws_instance" "target" {
for_each = local.volumes_with_attachment
filter {
name = "tag:Name"
values = [each.value.instance_name]
}
}
resource "aws_volume_attachment" "this" {
for_each = local.volumes_with_attachment
device_name = each.value.device_name
volume_id = aws_ebs_volume.this[each.key].id
instance_id = data.aws_instance.target[each.key].id
force_detach = each.value.force_detach
}
# DLM IAM role ===============================================================
data "aws_partition" "current" {}
resource "aws_iam_role" "dlm" {
for_each = local.create_dlm_role ? { role = true } : {}
name = "${var.dlm_policy_name}-role"
assume_role_policy = jsonencode({
Version = "2012-10-17"
Statement = [{
Effect = "Allow"
Principal = { Service = "dlm.amazonaws.com" }
Action = "sts:AssumeRole"
}]
})
tags = local.tags
}
resource "aws_iam_role_policy_attachment" "dlm" {
for_each = local.create_dlm_role ? { role = true } : {}
role = aws_iam_role.dlm["role"].name
policy_arn = "arn:${data.aws_partition.current.partition}:iam::aws:policy/service-role/AWSDataLifecycleManagerServiceRole"
}
# DLM snapshot lifecycle policy ==============================================
resource "aws_dlm_lifecycle_policy" "this" {
for_each = var.snapshot_schedules
description = each.value.name
execution_role_arn = local.dlm_role_arn
state = "ENABLED"
policy_details {
resource_types = ["VOLUME"]
target_tags = each.value.target_tags
schedule {
name = each.value.name
create_rule {
interval = each.value.interval
interval_unit = each.value.interval_unit
times = each.value.times
}
retain_rule {
count = each.value.retain_count
}
tags_to_add = merge(local.tags, { SnapshotCreator = "DLM" })
copy_tags = true
}
}
tags = local.tags
depends_on = [aws_iam_role_policy_attachment.dlm]
}
|