【问题标题】:Resource plan for creation although count evaluates to false用于创建的资源计划,尽管 count 评估为 false
【发布时间】:2022-01-16 21:03:02
【问题描述】:

我有以下变量

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     = ""
}

由以下 Terraform 资源使用:

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
}

现在,我的理解是 aws_iam_policy_documentaws_iam_policyaws_iam_role_policy_attachment 只有在 var.policies 不为空时才会创建。

但是,这些资源在调用它们时仍然是计划创建的

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.

为什么? AFAIK,policies 默认设置为[],因此不应计划创建资源。

我错过了什么?

【问题讨论】:

    标签: amazon-web-services terraform terraform-provider-aws


    【解决方案1】:

    默认设置为 []

    实际上它设置为list(string)的数据类型。因此,您的条件var.policies != [] 始终为真,这就是始终创建资源的原因。 []list(string) 不同。

    通常您会改为执行以下操作:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-01-04
      • 2011-06-14
      • 2015-03-15
      • 1970-01-01
      • 1970-01-01
      • 2016-06-20
      • 2012-06-12
      相关资源
      最近更新 更多