Home > OS >  Terraform dynamic group creation
Terraform dynamic group creation

Time:10-28

In my below terraform code I am trying to assign groups to the instances. But for the instances test1, test2 i am able to assign groups app1, app2, app3. But I want to assign groups app1,app2,app3 to test1 instance, groups t1,t2,t3 to test2 instance. Is there any logic that I am missing in the group_assignments block. Thanks.

locals {
  instances = [
    {
      instance  = "test1"
      baseUrl   = "url"
      subDomain = "sd"
      groups = [
        "app1",
        "app2",
        "app3",
      ]
},
    {
      instance  = "test2"
      baseUrl   = "url2"
      subDomain = "sd2"
      groups = [
        "t1",
        "t2",
        "t3",
      ]
},
  ]
}
resource "okta_group" "press" {
  for_each = { for k, instance in flatten(local.instances[*].groups) : k => instance }
  name     = each.value
}
resource "okta_app_saml" "press2" {
  for_each                   = { for k, instance in local.instances : k => instance }
  label                      = "press-${each.value.instance}"
  preconfigured_app          = "press"
}
resource "okta_app_group_assignments" "assignment" {
  for_each = { for k, instance in local.instances : k => instance }
  app_id   = okta_app_saml.press2[each.key].id
  dynamic "group" {
    for_each = each.value.groups
    content {
      id = okta_group.press[group.value].id
    }
  }
}

CodePudding user response:

I think it should be:

resource "okta_group" "press" {
  for_each = toset(flatten(local.instances[*].groups))
  name     = each.value
}

This way you can refer to individual instances of okta_group, as okta_group.press["app1"], okta_group.press["t1"] and so on.

  • Related