Home > other >  Resource plan for creation although count evaluates to false
Resource plan for creation although count evaluates to false

Time:12-14

I have the following variables

variable "policies" {
  type        = list(string)
  description = "List of policy document to attach to the IAM Role."
  default     = []
}

variable "policy_name" {
  type        = string
  description = "Name of the policy attached to the IAM Role."
  default     = null
}

variable "policy_description" {
  type        = string
  description = "Description of the policy attached to the IAM Role."
  default     = ""
}

Which are used by the following Terraform resources:

resource "aws_iam_role" "this" {
  name               = var.role_name
  assume_role_policy = var.assume_role_policy
}

data "aws_iam_policy_document" "this" {
  count                   = var.policies != [] ? 1 : 0
  source_policy_documents = var.policies
}

resource "aws_iam_policy" "this" {
  count       = var.policies != [] ? 1 : 0
  name        = var.policy_name
  description = var.policy_description
  policy      = data.aws_iam_policy_document.this[count.index].json
}

resource "aws_iam_role_policy_attachment" "this" {
  count      = var.policies != [] ? 1 : 0
  policy_arn = aws_iam_policy.this[count.index].arn
  role       = aws_iam_role.this.name
}

Now, my understanding is that aws_iam_policy_document, aws_iam_policy and aws_iam_role_policy_attachment are to be created only when var.policies is not empty.

However, these resources are still plan for creation when calling them like

module "iam_role_batch" {
  source             = "./resources/iam/role"
  role_name          = local.iam_role_batch_service_name
  assume_role_policy = data.aws_iam_policy_document.batch_service.json
}
# module.iam_role_batch.aws_iam_policy.this[0] will be created
  resource "aws_iam_policy" "this" {
      arn       = (known after apply)
      id        = (known after apply)
      name      = (known after apply)
      path      = "/"
      policy    = jsonencode(
          {
              Statement = null
              Version   = "2012-10-17"
          }
      )
      policy_id = (known after apply)
      tags_all  = (known after apply)
  }

# module.iam_role_batch.aws_iam_role_policy_attachment.this[0] will be created
  resource "aws_iam_role_policy_attachment" "this" {
      id         = (known after apply)
      policy_arn = (known after apply)
      role       = "xxxxxxx"
  }

Plan: 2 to add, 0 to change, 0 to destroy.

Why? AFAIK, policies is by default set to [], so the resources should not be planned for creation.

What do I miss?

CodePudding user response:

is by default set to []

Actually it is set to data type of list(string). So your condition var.policies != [] is always true, and that is why the resource is always created. [] is not the same as list(string).

Usually you would do the following instead:

count       = length(var.policies) > 0 ? 1 : 0
  • Related