0
votes

Good morning,

I’m using Terraform 0.12 with the Azure Provider 2.0.0. I have the following block to retrieve all subscriptions starting with “sub-”:

data "azurerm_subscriptions" "mgt" {
    display_name_prefix = "sub-"
}

Now I would like to somehow automatically create the different “azurerm_subscription” objects from this one. Is there any way to kind of loop over all those subscriptions and create the appropriate “azurerm_subscription” objects?

Thanks!

1
AFAIK, the display_name_prefix is not expected in data "azurerm_subscription"block, what do you try to do? Also, you can use this data source to access information about an existing Subscription. You can not create new subscription objects from it.Nancy Xiong
The display_name for filtering works just fine. The output gives me back all the subscriptions according to the filter. What I’m trying to do is having one single data source with all subscriptions instead of having e.g. 20 times a data source of type “azurerm_subscription”. The only problem I have then, is that I cannot easily access the attributes of a specific subscription, as I have to access them by index and not by e.g. its name.azuresma
Yes, you have to access the attributes of a specific subscription by index because the data "azurerm_subscriptions" output all the filtered subscriptions. It's a list not a string of subscription. So is this your problem?Nancy Xiong
Currently, the "looping" constructs in Terraform require the values to be known before runtime. You could for_each through a pre-defined list of subscriptions, but not through a list populated by running Terraform. terraform.io/docs/configuration/…logicaldiagram

1 Answers

1
votes

You can find index of your subscription, then refer to that index:

data "azurerm_subscriptions" "available" {
}

locals {
  subscription_index = index(data.azurerm_subscriptions.available.subscriptions.*.display_name, "mysubscription")
}

output "azurerm_subscription" {
  value = element(data.azurerm_subscriptions.available.subscriptions, local.subscription_index)
}

You can also create map from the "azurerm_subscriptions". Then create "azurerm_subscription" using for_each and reference to specific data using name:

locals {
  subscriptions_map = {
    for obj in data.azurerm_subscriptions.available.subscriptions.* : obj.display_name => obj
  }
}

data "azurerm_subscription" "sub" {
  for_each = local.subscriptions_map

  subscription_id     = each.value.subscription_id
}

output "data" {
  value = data.azurerm_subscription.sub["mysubscription"].subscription_id
}