Trying to create multiple variable groups in Azure Devops using Terraform

https://registry.terraform.io/providers/microsoft/azuredevops/latest/docs/resources/variable_group

It is easy to create a single variable group using the azuredevops_variable_group resource block, but I am not able to create multiple variable groups.

i declared the variable as a map of map of strings:

var_groups = {
vargroup1 = {
key11 = “value11”,
key12 = “value12”,
key13 = “value13”
},
vargroup2 = {
key21 = “value21”,
key22 = “value22”,
key23 = “value23”
}
}

I am trying to create two variable groups and each var group will have 3 key vars inside them.

locals {
vargroups = flatten([for groupname, groupvars in var.var_groups:
flatten([for varname, varvalue in groupvars:
{
“groupname” = groupname
“varname” = varname
“varvalue” = varvalue
}
])
])
}

Create a variable group

resource “azuredevops_variable_group” “var-group” {
for_each = {for var_group_name, var_group_vars in local.vargroups : var_group_name => var_group_vars}
project_id = var.existing_ado_project == “” ? azuredevops_project.ado-project[0].id : data.azuredevops_project.existing-ado-project[0].id
name = each.value.groupname
description = “Managed by Terraform”
allow_access = true
variable {
name = each.value.varname
value = each.value.varvalue
}
}

This is not working as expected :cry: any help would be much appreciated.

Thanks.

I was able to get this done by changing the way I declared the variable.
var_groups = {
vargroup1 = [
{
name = “key1”
value = “value1”
},
{
name = “key2”
value = “value2”
}
]
vargroup2 = [
{
name = “key3”
value = “value3”
},
{
name = “key4”
value = “value4”
}
]
}

resource “azuredevops_variable_group” “var-group” {
for_each = {for vargroupname, vargroupvars in var.var_groups : vargroupname => vargroupvars}
project_id = var.existing_ado_project == “” ? azuredevops_project.ado-project[0].id : data.azuredevops_project.existing-ado-project[0].id
name = each.key
description = “Managed by Terraform”
allow_access = true
dynamic variable {
for_each = each.value
content {
name = variable.value.name
value = variable.value.value
}
}
}

not sure if this is the best way to do it… but still got the job done.