kubernetes Terraform错误:缺少资源示例键

fkaflof6  于 2023-03-29  发布在  Kubernetes
关注(0)|答案(1)|浏览(98)

我不知道我做错了什么。尝试在地形中创建角色和角色绑定。
我有这样的地形:

resource "kubernetes_cluster_role" "allow_port_forward" {
  count = (
    (var.env != "prod")
    && (var.env != "infra")
  ) ? 1 : 0
  metadata {
    annotations = {
      "CCE.com/IAM" : "true"
    }
    name = "allow-port-forward"
  }

  rule {
    api_groups = ["rbac.authorization.k8s.io"]
    resources  = ["pods", "pods/portforward"]
    verbs      = ["get", "list", "create"]
  }
}

resource "kubernetes_cluster_role_binding" "allow_port_forward" {
  count = (
    (var.env != "prod")
    && (var.env != "infra")
  ) ? 1 : 0
  metadata {
    annotations = {
      "CCE.com/IAM" : "true"
    }
    name = "allow-port-forward"
  }

  role_ref {
    api_group = "rbac.authorization.k8s.io"
    kind      = "ClusterRole"
    name = kubernetes_cluster_role.allow_port_forward.metadata[0].name

  }
  subject {
    # developer group
    kind      = "Group"
    name      = "0f2762d3df0025dd3f71c00207c49c39"
    api_group = "rbac.authorization.k8s.io"
  }
}

Terraform计划返回这个。它抱怨计数,但不确定该怎么办。

Error: Missing resource instance key
│ 
│   on modules/rbac/cluster_role_binding/main.tf line 98, in resource "kubernetes_cluster_role_binding" "allow_port_forward":
│   98:     name = kubernetes_cluster_role.allow_port_forward.metadata[0].name
│ 
│ Because kubernetes_cluster_role.allow_port_forward has "count" set, its attributes must be accessed on specific instances.
│ 
│ For example, to correlate with indices of a referring resource, use:
│     kubernetes_cluster_role.allow_port_forward[count.index]
qjp7pelc

qjp7pelc1#

由于您正在使用count元参数创建kubernetes_cluster_role资源:

count = (
    (var.env != "prod")
    && (var.env != "infra")
  ) ? 1 : 0

这意味着如果条件为真,则将正好有一个kubernetes_cluster_role的示例。现在,count元参数添加了索引,因此为了引用使用count创建的任何资源,您需要知道确切的索引或使用count.index对象。由于第二个资源,即kubernetes_cluster_role_binding,使用相同的count元参数逻辑,您可以通过以下方式修复此问题:

resource "kubernetes_cluster_role_binding" "allow_port_forward" {
  count = (
    (var.env != "prod")
    && (var.env != "infra")
  ) ? 1 : 0
.
.
.

  role_ref {
    api_group = "rbac.authorization.k8s.io"
    kind      = "ClusterRole"
    name = kubernetes_cluster_role.allow_port_forward[count.index].metadata[0].name
  }
.
.
.
}

documentation有一些很好的例子。

相关问题