简体   繁体   中英

Terraform throwing error with for_each while doing KV IAM

I want to assign my Terraform Service Principal "KV Secrets User", "KV Contributor" RBAC roles My code is given below

Storing SQL PWD in the vault

 resource "azurerm_key_vault_secret" "app-pwd" {
      name         = "sql-pass"
      value        = azurerm_mssql_server.primary.administrator_login_password
      key_vault_id = data.azurerm_key_vault.my-kv.id
    }
    
    resource "azurerm_role_assignment" "kv-iam" {
      for_each           = data.azurerm_role_definition.builtin[each.key]
      scope              = var.subscription_id
      role_definition_name = local.role_name[each.value]
      principal_id       = data.azurerm_client_config.current.id
    }


provider "azurerm" {
  tenant_id       = var.tenant_id
  client_id       = var.client_id
  client_secret   = var.client_secret
  subscription_id = var.subscription_id
  features {}
}

data "azurerm_key_vault" "my-kv" {
  name                = "testhalvault"
  resource_group_name = "Dev-Rg"
}

data "azurerm_client_config" "current" {}

data "azurerm_role_definition" "builtin" {
  for_each =  toset(local.role_name)
  name = format("%s", each.key)
}

locals {
  role_name = [
  "Key Vault Secrets User",
  "Key Vault Administrator"
  ]
}

I get the below error while doing TF Plan

 Error: Reference to "each" in context without for_each
│ 
│   on resources.tf line 54, in resource "azurerm_role_assignment" "kv-iam":
│   54:   for_each           = data.azurerm_role_definition.builtin[each.key]
│ 
│ The "each" object can be used only in "module" or "resource" blocks, and
│ only when the "for_each" argument is set.
╵
Operation failed: failed running terraform plan (exit 1)

How do i assign multiple RBAC Built-In Roles to my TF SP

通常您会执行以下操作:

      for_each           = data.azurerm_role_definition.builtin

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM