How to update Azure subscription tags with Terraform?

620 Views Asked by At

I'm trying to manage Azure tags on the subscription level (not resources or resource groups). We are not creating the subscriptions with Terraform and we cannot. After we create the subscription, we create a configuration template for that subscription. In there, we manage things like access control and ownership records. Here's what a standard config template for a subscription looks like.

module "subscription-project-pegasus" {
  source                     = "./modules/subscription/"

  subscription_access = [
    {
      aad_group = "all-employees-group"
      role      = "Reader"
    },
    {
      spn = "spn-pegasus"
      role = "Contributor"
    }
  ]

  ownership = {
    team = "Team Pegasus",
    pagerduty_id = "pegasus"
  }
}

I would like to add another object here with tags that I can apply at the subscription level.

tags = {
    owner = "pegasus"
    environment = "nonprod"
  }

That custom module ./modules/subscriptions does the provisioning of role assignments using the azurerm_role_assignment module. However, I cannot find a module that can do tagging besides the main azurerm_subscription module that's primarily used to provision subscriptions as well. If I use this, I believe Terraform is going to start tracking the state of the subscriptions and that won't be ideal.

I'm looking for a way to add these tags on the subscription level without using the azurerm_subscription module. Please advise!

1

There are 1 best solutions below

1
Vinay B On BEST ANSWER

I tried to add/update Azure subscription tags with Terraform without using the azurerm_subscription module and successfully provisioned the requirement.

If you wish to manage tags on a subscription level without using the azurerm_subscription module due to its state tracking, you can achieve this using a local-exec provisioner to run Azure CLI commands to add tags to the subscription.

My terraform configuation

main.tf

variable "subscription_id" {
  description = "The ID of the Azure subscription."
  type        = string
}

variable "tags" {
  description = "A map of tags to assign to the resource."
  type        = map(string)
  default     = {}
}


resource "null_resource" "subscription_tags" {
  provisioner "local-exec" {
    command = <<EOT
      az account set --subscription "${var.subscription_id}"
      az tag create --resource-id "/subscriptions/${var.subscription_id}" --tags ${join(" ", [for k, v in var.tags : "${k}=${v}"])}
    EOT
  }

  triggers = {
    tags = jsonencode(var.tags)
  }
}

Output:

Here I was using the vinay as owner name and env as non prod

Here I was using the vinay as the owner name and env as non-prod

enter image description here