pkaramol
pkaramol

Reputation: 19352

Make terraform module creation fail based on a condition

I am trying to leverage precondition hook to check for an input to a module creation in terraform.

module "groups" {

  source   = "../path/to/groups"
  for_each = var.groups.groups

  name     = each.key
  type     = each.value.type
  policies = each.value.policies
  depends_on = [
    module.policies
  ]
  
  lifecycle {

    precondition {
      condition = alltrue([ for item in self.policies : 
      alltrue([ for p in item : contains(locals.policies_list, p) ]) ] ) 
      error_message = format("Attempt to create a group with a non existing policy")
    }
  }

}

However, although:

terraform --version --json
{
  "terraform_version": "1.3.7",
  "platform": "linux_amd64",
  "provider_selections": {},
  "terraform_outdated": false
}

This fails:

The block type name "lifecycle" is reserved for use by Terraform in a future version.

Is this because the specific functionality is not available in terraform for module creation? Is there a way around making my module creation fail based on the above condition?

Upvotes: 0

Views: 1132

Answers (1)

pkaramol
pkaramol

Reputation: 19352

Unfortunately the lifecycle block is not available for a module.

A way around this is the following

module "groups" {

  source   = "../path/to/groups"
  for_each = var.groups.groups

  name     = each.key
  type     = each.value.type
  policies = each.value.policies
  depends_on = [
    null_resource.group_check,
    module.policies
  ]
}

resource "null_resource" "group_check" {
  for_each = var.groups.groups

  lifecycle {

    precondition {
      condition     = alltrue([for p in each.value.policies : contains(local.policies_list, p)])
      error_message = format("Attempt to create a group with a non existing policy")
    }
  }

  depends_on = [
    module.policies
  ]
}

Upvotes: 1

Related Questions