Search code examples
amazon-web-servicesamazon-ec2terraformlifecyclesnapshot

aws_dlm_lifecycle_policy's retain_rule - can you mix retain rules?


Is it possible to include both count and interval (with the corresponding interval_unit) conditions in the aws_dlm_lifecycle_policy.policy_details.schedule.**retain_rule** within the single schedule policy?

What I'd like to achieve is to specify a backup policy to keep N last EBS snapshots but at the same time discards any of them that are older than a certain threshold.

data "aws_iam_policy_document" "dlm_assume_role" {
  statement {
    effect = "Allow"

    principals {
      type        = "Service"
      identifiers = ["dlm.amazonaws.com"]
    }

    actions = ["sts:AssumeRole"]
  }
}

resource "aws_iam_role" "dlm_lifecycle_role" {
  name               = "dlm-lifecycle-role"
  assume_role_policy = data.aws_iam_policy_document.dlm_assume_role.json
}

data "aws_iam_policy_document" "dlm_lifecycle" {
  statement {
    effect = "Allow"

    actions = [
      "ec2:CreateSnapshot",
      "ec2:CreateSnapshots",
      "ec2:DeleteSnapshot",
      "ec2:DescribeInstances",
      "ec2:DescribeVolumes",
      "ec2:DescribeSnapshots",
    ]

    resources = ["*"]
  }

  statement {
    effect    = "Allow"
    actions   = ["ec2:CreateTags"]
    resources = ["arn:aws:ec2:*::snapshot/*"]
  }
}

resource "aws_iam_role_policy" "dlm_lifecycle" {
  name   = "dlm-lifecycle-policy"
  role   = aws_iam_role.dlm_lifecycle_role.id
  policy = data.aws_iam_policy_document.dlm_lifecycle.json
}

resource "aws_dlm_lifecycle_policy" "ebs_snapshot" {
  description        = "EC2 EBS DLM lifecycle policy"
  execution_role_arn = aws_iam_role.dlm_lifecycle_role.arn
  state              = "ENABLED"

  policy_details {
    resource_types = ["VOLUME"]

    schedule {
      name = "${var.name_prefix} EC2 EBS backup policy"

      create_rule {
        interval      = var.ebs_snapshot_interval
        interval_unit = "HOURS"
      }

      retain_rule {
        interval      = var.ebs_snapshot_max_retain_period
        interval_unit = "DAYS"
        #### <<<< insert `count` here (?)
      }

      copy_tags = true
    }

    target_tags = {
      Name = "${var.name_prefix}"
    }
  }
}

On one hand, according to the Terraform resource docs these two parameters are not exclusive towards each other but on the other, it seems to be impossible to recreate such configuration in the AWS Web Console.


Solution

  • TL;DR: It seems that currently it's not possible.

    If someone intended to use ...schedule.retain_rule and specify the COUNT along the ...schedule.deprecate_rule (period threshold) then unfortunately it wouldn't work either - there's a bug in the resource documentation (link to the issue on GH)