# At this time, terraform does not support DLM AMI policies, only snapshots.
# So we do it ourselves
# 
# NOTE: This will not update an existing policy, but will create one if it's missing.

# Grab the current policy name. This turned out to be unnecessary for my purposes, but
# will be useful if in the future we decide to implement a 'modify' resource.
#
# WARNING: External data sources are run before the apply, and even before any decision
#          is made whether or not to apply, so do not make changes in such a script.
data "external" "get_dlm_policies" {
  program = ["bin/get_current_dlm_policies", var.aws_partition, var.aws_region, var.aws_account_id, var.account_name]
}

# useful for debugging, but don't leave it uncommented or itll report a change on second apply:
#output "dlm_policies" {
#  value = data.external.get_dlm_policies.result
#}

# In rare cases, you may need/want to manually recreate this. To do so, run
#    terragrunt taint null_resource.create_dlm_policy
resource "null_resource" "create_dlm_policy" {
  #count = data.external.get_dlm_policies.result["PolicyId"] == "null" ? 1 : 0
  #count = data.external.get_dlm_policies.result["PolicyId"] == "policy-02af49210b5b375d5" ? 1 : 0

  # Could maybe find some sort of trigger here, in case the DLM is deleted?

  provisioner "local-exec" {
    command = "bin/create_dlm_policy ${var.aws_partition} ${var.aws_region} ${var.aws_account_id} ${var.account_name}"
  }
}
