Exporting Values to CSV after Creation

I have following code which creates ACI tenants from a CSV file:

terraform {
required_providers {
aci = {
source = “CiscoDevNet/aci”
}
}
}

User Creds

variable “user” {
description = “Login Credentials”
type = map
default = {
username = “admin”
password = “ciscopsdt”
url = “https://sandboxapicdc.cisco.com
}
}

Authenticate with user-id and password

provider “aci” {
username = var.user.username
password =var.user.password
url = var.user.url
insecure = true
}

Import and decode csv data

locals {
csv_data = file(“./variables3.csv”)
instances = csvdecode(local.csv_data)
}

Create tenants for values under the tn_id column

resource “aci_tenant” “example” {
#for_each = { for inst in local.instances : inst.tn_id => inst }
for_each = { for inst in local.instances : inst.UID => inst }
name = each.value.tn_id
}

output IDs to csv

resource “local_file” “UpdatedVariables” {
for_each = { for inst in local.instances : inst.UID => inst }
content = templatefile(“variables3.csv”,
{
“${each.value.UID}” = aci_tenant.example[each.value.UID].id
}
)
filename = “variables_Upd.csv”
}

With the CSV input being:

UID,tn_id,AP,EPG,ID
aX1,TNT_1,AP_1,EPG_1, ${aX1}

aX5,TNT_2,AP_1,EPG_1, ${aX5}

The aim here being to get the id of the created tenants into the csv file. I am unsure how to nest the for_each statement and how to name the key in the content to get the desired result.

Error: Invalid function argument
on main.tf line 47, in resource “local_file” “UpdatedVariables”:
46: content = templatefile(“variables3.csv”,
47: {
48: “{each.value.UID}” = aci_tenant.example[each.value.UID].id
49: }
50: )
|----------------
| aci_tenant.example is object with 2 attributes
| each.value.UID is “aX5”
Invalid value for “vars” parameter: vars map does not contain key “aX1”,
referenced at variables3.csv:2,25-28.
Error: Invalid function argument
on main.tf line 47, in resource “local_file” “UpdatedVariables”:
46: content = templatefile(“variables3.csv”,
47: {
48: “{each.value.UID}” = aci_tenant.example[each.value.UID].id
49: }
50: )
|----------------
| aci_tenant.example is object with 2 attributes
| each.value.UID is “aX1”
Invalid value for “vars” parameter: vars map does not contain key “aX5”,
referenced at variables3.csv:3,25-28.

1 Like