Skip to main content
Jorge Bernhardt Jorge Bernhardt
  1. Posts/

Terraform - Deploy and manage Subscription Budgets

·997 words·5 mins· 100 views · 5 likes ·
Budgets Microsoft Microsoft Azure Terraform

Hi! Today, I’d like to share a helpful tip on how you can efficiently manage your Azure resources and services while keeping your cloud spending in check. With Azure Budgets, you can easily set budget thresholds and receive alerts to monitor your costs proactively.

By integrating this service with Terraform, you can automate the implementation and management of these budgets, ensuring standardized control of your cloud spend. It’s a powerful combination to save time and money.

Prerequisites>

Prerequisites #

  • You need Terraform CLI on your local machine, if you’re new to using Terraform to deploy Microsoft Azure resources, then I recommend you check out this link.
  • A text editor or IDE of your choice (Visual Studio Code with Terraform extension is my recommendation)
Declare Azure Provider in Terraform>

Declare Azure Provider in Terraform #

The provider.tf file in Terraform is used to specify and configure the providers used in your Terraform configuration. A provider is a service or platform where the resources will be managed. This could be a cloud provider like Microsoft Azure, AWS, Google Cloud, etc.

This file is important because it tells Terraform which provider’s API to use when creating, updating, and deleting resources. Without it, Terraform wouldn’t know where to manage your resources.

provider "azurerm" {   
    features {} 
    }
Create Azure subscription budgets using Terraform>

Create Azure subscription budgets using Terraform #

In the case of Azure budget deployment, the main.tf file contains the following key components:

  • Subscription: This block gets the details of the current Azure subscription you’re using. This is useful for getting the subscription ID needed to create the budgets.

  • Budget: This block defines a resource for each budget you want to create. The for_each statement allows you to create multiple budgets from the budget variable’s elements.

  • time_period: This block defines the period of time during which the budget will be applied.

  • notification: This block uses the dynamic keyword to create a notification block for each item in the notifications list of the budget object. These notification blocks define when a notification should be sent based on spend, who it should be sent to, and what role that person should have in the Azure subscription.

// Get subscription details
data "azurerm_subscription" "subscription" {}

// Create consumption budgets
resource "azurerm_consumption_budget_subscription" "budget" {
  for_each = { for b in var.budgets : b.name => b }

  name            = each.value.name
  amount          = each.value.amount
  time_grain      = each.value.time_grain
  subscription_id = data.azurerm_subscription.subscription.id
  
  // Set the time period for the budget  
  time_period {
    start_date = each.value.start_date
    end_date   = each.value.end_date
  }

  // Create notifications for each budget
  dynamic "notification" {
    for_each = each.value.notifications
    content {
      enabled        = notification.value.enabled
      threshold      = notification.value.threshold
      operator       = notification.value.operator
      threshold_type = notification.value.threshold_type
      contact_emails = notification.value.contact_emails
      contact_roles  = notification.value.contact_roles
    }
  }
}
Declaration of input variables>

Declaration of input variables #

The variables.tf file in Terraform defines the variables I will use in the main.tf file. These variables allow for more flexibility and reusability in the code. In this example, the variables are defined in the variables.tf include:

  • budgets: This variable is a list of objects, where each object represents an Azure budget.
variable "budgets" {
  description = "List of budgets"
  type = list(object({
    name       = string 
    amount     = number 
    time_grain = string // Valid values are: "Monthly", "Quarterly", "Annually"
    start_date = string // Any valid start date in "YYYY-MM-DDT00:00:00Z" format
    end_date   = string // Any valid end date in "YYYY-MM-DDT00:00:00Z" format
    notifications = list(object({
      enabled        = bool 
      threshold      = number
      operator       = string  // Valid values are: "EqualTo", "GreaterThan", "GreaterThanOrEqualTo"
      threshold_type = string  // Valid values are: "Actual", "Forecasted"
      contact_emails = list(string) 
      contact_roles  = list(string)  // Valid values are: "Owner", "Reader", "Contributor"
    }))
  }))
}
Declaration of output values>

Declaration of output values #

The output.tf file in Terraform extracts and displays information about the resources created or managed by your Terraform configuration. These outputs are defined using the output keyword and can be used to return information that can be useful for the user, for other Terraform configurations, or for programmatically using the information in scripts or other tools.

In this example, the output.tf file returns information about the IDs and names of the Azure budgets created.

Once Terraform has finished applying your configuration, it will display the defined outputs.

// Output the IDs of the created budgets
output "budget_ids" {
  description = "The IDs of the created budgets"
  value       = { for b in azurerm_consumption_budget_subscription.budget : b.name => b.id }
}

// Output the names of the created budgets
output "budget_names" {
  description = "The names of the created budgets"
  value       = [for b in azurerm_consumption_budget_subscription.budget : b.name]
}
Executing the Terraform Deployment>

Executing the Terraform Deployment #

Now that you’ve declared the resources correctly, it’s time to take the following steps to deploy them in your Azure environment.

  • Initialization: To begin, execute the terraform init command. This will initialize your working directory that holds the .tf files and download the provider specified in the provider.tf file, and configure the Terraform backend. I suggest looking at this link if you’re curious about the process.

  • Planning: Next, execute the terraform plan. This command creates an execution plan and shows Terraform’s actions to achieve the desired state defined in your .tf files. This gives you a chance to review the changes before applying them.

  • Apply: When you’re satisfied with the plan, execute the terraform apply command. This will implement the required modifications to attain the intended infrastructure state. Before making any changes, you will be asked to confirm your decision.

  • Inspection: After applying the changes, you can use terraform show command to see the current state of your infrastructure.

  • Destroy (optional): when a project is no longer needed or when resources have become outdated. You can use the terraform destroy command. This will remove all the resources that Terraform has created.

References and useful links #

Thank you for taking the time to read my post. I sincerely hope that you find it helpful.