Amman
Amman

Reputation: 317

how to use json file in terraform

I have the following JSON file and using it while creating users in terraform

{
    "[email protected]" : [
        {
        "name" : "abc",
        "description" : 100,
        },        
        {
        "name" : "efg",
        "description" : 100
        },        
        {
        "name" : "wer",
        "description" : 100
        }
    ],
    "[email protected]" : [
        {
        "name" : "xyz",
        "description" : 100
        },
        {
        "name" :  "qwe",
        "description" : 100        
        }
    ]
}

I tried with a few things but it errors out ... while usin in the resource creation. I'm unable to figure out on how to grab the keys, values

resource "oci_identity_user" "users" {
    count = keys(local.users)[*] 
    
    compartment_id = var.tenancy_ocid
    description = count.index[description]
    name = count.index[name]
    email = count.index[email]
}


Error: Invalid index
│
│   on local.tf line 14, in locals:
│   14:   services = keys(local.users[1])
│     ├────────────────
│     │ local.odsc_serivices is object with 2 attributes
│

Upvotes: 1

Views: 438

Answers (1)

Ervin Szilagyi
Ervin Szilagyi

Reputation: 16775

Since you have two lists in your users object, you have to concatenate them. You can do this with combining flatten and values functions. Moreover, I suggest using for_each instead of count:

resource "oci_identity_user" "users" {
  for_each = { for index, value in flatten(values(local.users)) : index => value }

  compartment_id = var.tenancy_ocid
  description    = each.value.name
  name           = each.value.description
  email          = each.value.email
}

Update:

resource "oci_identity_user" "users" {
  for_each = {
    for index, value in flatten([
      for email, value in local.users : [
        for user in value : { email : email, name : user.name, description : user.description }
      ]
    ]) : index => value
  }

  compartment_id = var.tenancy_ocid
  description    = each.value.name
  name           = each.value.description
  email          = each.value.email
}

Upvotes: 1

Related Questions