Automation, Azure, Cost, DevOps, Professional, Terraform

Terraform to Deploy Azure Consumption Budgets

If you missed it azurerm v2.59 of Terraform supports consumption resources. This is big as it allows us to apply an Azure Consumption Budget via Terraform. What I’ll walkthrough here is how to set that budget at the resource group via Terraform.

The Terraform code will look like:

resource "azurerm_consumption_budget_resource_group" "rg_budget" {
  name       = "${azurerm_resource_group.rg_our_resource_group.name}_budget"
  amount     = 100
  time_grain = "Monthly" // Monthly, Quarterly, Annually
  time_period {
    start_date = formatdate("YYYY-MM-01'T'hh:mm:ssZ",timestamp()) //Budget needs to be first day of current month for start
  }
  resource_group_id = azurerm_resource_group.rg_our_resource_group.id
  notification {
    threshold      = 80                     // 0-1000
    operator       = "GreaterThanOrEqualTo" // EqualTo, GreaterThan, GreaterThanOrEqualTo
    contact_emails = ["johndoe@hotmail.com"]
  }
  lifecycle {
    ignore_changes = [
      time_period
    ]
  }
}

This is pretty straight forward just update the “rg_our_reosurce_group” with a reference to the resource group. An important callout here that is a bit tricky is the time_period block. This block first requires the date time to be in RFC 3339 format. This block also requires a start date and that start date must be the first of the month that the deployment is running in. This means we can’t backdated. The default end_date which we have not included will be ten years from the deployment. If you are familiar with Terraform then you also realize that this can cause some headache. Every time we run a plan Terraform will detect changes and will attempt to change the resource when in theory, we may not want that extra noise.

To get around this we use the lifecycle block:

  lifecycle {
    ignore_changes = [
      time_period
    ]
  }

This will tell our Terraform process to ignore any of the attributes under time_period. This will help us in not redeploying an unnecessary budget resource every time we run a plan/apply.

There you have it! Pretty simple right! This little snippet of code can help set Azure Consumption Budget’s as part of the terraform deployment.