'Move null_data_source to locals in terraform

I have the following resources:

locals {
  ram_roles               = toset(distinct(flatten(concat(var.rbac_bindings.admin, var.rbac_bindings.ops))))

data "alicloud_ram_roles" "ad_roles" {
  name_regex = "^K8S-.*"
}

data "null_data_source" "ram_role_ids" {
  for_each = local.ram_roles
  inputs = {
    id = [for x in data.alicloud_ram_roles.ad_roles.roles : x.id if x.name == each.key][0]
  }
}

tfvars:

rbac_bindings = {
    admin      = ["K8S-Admin", "K8S-DBAdmin"]
    ops        = ["K8S-Admin", "K8S-NetworkAdmin"]
}

Then null_data_resource is used:

resource "alicloud_cs_kubernetes_permissions" "admin" {
  for_each = toset(var.rbac_bindings.admin)
  uid      = data.null_data_source.ram_role_ids[each.key].inputs.id

Output for data.null_data_source.ram_role_ids is

output  = {
      K8S-Admin        = {
          inputs               = {
              "id" = "384343534546567676"
          }
          outputs              = {
              "id" = "194564564534343552"
          }
        }
      K8S-DBAadmin = {
      ...

So i'm trying to move it to locals with:

ram_role_id = [for key in local.ram_roles: [for x in data.alicloud_ram_roles.ad_roles.roles : x.id if x.name == key][0]]

but it gives me only ids, and using it later with for each uid = lookup(local.ram_role_id, each.key) gives an error. How to correctly move it to local where for_each is used?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source