How create multiple VCN at the same time

135 Views Asked by At

I have a problem, i need create more than one VCN.

I want to set variables into a JSON file. like this:

init_values.json

{
  "terraform": {
    "tenancy_ocid": "ocid1.ten.xxxxxxxxxxxxxxxxxx",
    "user_ocid": "ocid1.user..xxxxxxxxxxxxxxxxxx",
    "private_key_path": "/Users/user/.oci/oci_api_key.pem",
    "fingerprint": "a8:8e:.xxxxxxxxxxxxxxxxxx",
    "region": "eu-frankfurt-1"
  },
  "vcn": [
    {
      "name": "vcn_1",
      "cidr": "44.144.224.0/25"
    },
    {
      "name": "vcn_2",
      "cidr": "44.144.224.128/25"
    }
  ]
}

and my vcn.tf file lokks like this

locals {
  vcn_data = jsondecode(file("${path.module}/init_values.json"))

  all_vcn = [for my_vcn in local.vcn_data.vcn : my_vcn.name ]
  all_cidr = [for my_cidr in local.vcn_data.vcn : my_cidr.cidr ]
}


resource "oci_core_vcn" "these" {
  compartment_id  = local.json_data.COMPARTMENT.root_compartment
  display_name = local.all_vcn
  cidr_block = local.all_cidr
}

and provider.tf is:

provider "oci" {
  //alias             = "home"
  tenancy_ocid      = local.json_data.TERRAFORM.tenancy_ocid
  user_ocid         = local.json_data.TERRAFORM.user_ocid
  private_key_path  = local.json_data.TERRAFORM.private_key_path
  fingerprint       = local.json_data.TERRAFORM.fingerprint
  region            = local.json_data.TERRAFORM.region
}

and the error is the next:

│ Error: Incorrect attribute value type
│ 
│   on vcn.tf line 39, in resource "oci_core_vcn" "these":
│   39:   display_name = local.all_vcn
│     ├────────────────
│     │ local.all_vcn is tuple with 2 elements
│ 
│ Inappropriate value for attribute "display_name": string required.
╵

what could be my error, where i'm wrong

Thanks

1

There are 1 best solutions below

2
On

Probably, instead of:

all_cidr = [for my_cidr in local.vcn_data.vcn : my_vcn.cidr ]

it should be:

all_cidr = [for my_cidr in local.vcn_data.vcn : my_cidr.cidr ]

Update

You have to use count or for_each to create multiple vcns:

resource "oci_core_vcn" "these" {
  
  count = length(local.all_vcn)

  compartment_id  = local.json_data.COMPARTMENT.root_compartment

  display_name = local.all_vcn[each.index]
  cidr_block = local.all_cidr[each.index]
}