> ## Documentation Index
> Fetch the complete documentation index at: https://docs.costory.io/llms.txt
> Use this file to discover all available pages before exploring further.

# Azure Billing Setup

> Connect Azure Cost Management exports to Costory with a Google federated credential. Paste Azure client ID and tenant ID. No SAS token.

Costory reads Azure Cost Management exports from a storage container you own. Access uses an Azure AD app with a federated credential for Costory's Google service account, the same Client ID AWS already shows. In **Connect Azure**, you paste **Azure client ID** and **Azure tenant ID**. Costory does not store a SAS token on new connections.

The fastest path is the in-app **Azure CLI** or **Terraform** snippet (\~5 min). It fills in Costory's Google service account unique ID for you.

> [tab] Terraform
>
> To install and authenticate the provider, see [Terraform setup](https://docs.costory.io/setup/terraform.md).
>
> The example below creates the Cost Management exports, an Azure AD app with a Google federated credential, a container-scoped **Storage Blob Data Reader** role, and the Costory datasource. Send `client_id` and `tenant_id` with the storage account, container, and actuals/amortized paths. Do not send a SAS URL.
>
> ```hcl theme={null}
> terraform {
>   required_version = ">= 1.5"
>
>   required_providers {
>     azurerm = {
>       source  = "hashicorp/azurerm"
>       version = "~> 4.0"
>     }
>     azuread = {
>       source  = "hashicorp/azuread"
>       version = "~> 3.0"
>     }
>     azapi = {
>       source  = "Azure/azapi"
>       version = "~> 2.0"
>     }
>     random = {
>       source  = "hashicorp/random"
>       version = "~> 3.0"
>     }
>     time = {
>       source  = "hashicorp/time"
>       version = "~> 0.11"
>     }
>     costory = {
>       source  = "costory-io/costory"
>       version = "~> 0.2"
>     }
>   }
> }
>
> variable "costory_api_token" {
>   type        = string
>   description = "Costory API token."
>   sensitive   = true
> }
>
> variable "subscription_id" {
>   type        = string
>   description = "Azure subscription ID."
> }
>
> variable "location" {
>   type        = string
>   description = "Azure region for all resources."
>   default     = "West Europe"
> }
>
> variable "resource_group_name" {
>   type        = string
>   description = "Name of the resource group to create."
>   default     = "costory-cost-exports"
> }
>
> variable "storage_account_name_prefix" {
>   type        = string
>   description = "Prefix for the storage account name (a random suffix is appended for uniqueness). Azure requires 3-24 lowercase letters or numbers for the full name."
>   default     = "costexports"
> }
>
> variable "backfill_month_count" {
>   type        = number
>   description = "Number of past months to backfill (0 to skip)."
>   default     = 12
> }
>
> variable "run_backfill" {
>   type        = bool
>   description = "Set to true to trigger backfill runs. Use: terraform apply -var='run_backfill=true'"
>   default     = false
> }
>
> provider "azurerm" {
>   features {}
>   subscription_id = var.subscription_id
> }
>
> provider "azuread" {}
>
> provider "costory" {
>   token = var.costory_api_token
> }
>
> data "azurerm_client_config" "current" {}
>
> data "costory_service_account" "current" {}
>
> resource "azurerm_resource_group" "cost_exports" {
>   name     = var.resource_group_name
>   location = var.location
> }
>
> resource "random_string" "storage_suffix" {
>   length  = 8
>   special = false
>   upper   = false
> }
>
> resource "azurerm_storage_account" "cost_exports" {
>   name                     = "${var.storage_account_name_prefix}${random_string.storage_suffix.result}"
>   resource_group_name      = azurerm_resource_group.cost_exports.name
>   location                 = azurerm_resource_group.cost_exports.location
>   account_tier             = "Standard"
>   account_replication_type = "LRS"
>   min_tls_version          = "TLS1_2"
> }
>
> resource "azurerm_storage_container" "billing" {
>   name               = "billing-exports"
>   storage_account_id = azurerm_storage_account.cost_exports.id
> }
>
> resource "time_static" "export_start" {}
>
> locals {
>   actuals_export_name   = "costory-actuals-${random_string.storage_suffix.result}"
>   amortized_export_name = "costory-amortized-${random_string.storage_suffix.result}"
> }
>
> resource "azapi_resource" "actuals" {
>   type      = "Microsoft.CostManagement/exports@2025-03-01"
>   name      = local.actuals_export_name
>   parent_id = "/subscriptions/${var.subscription_id}"
>
>   body = {
>     properties = {
>       definition = {
>         type      = "ActualCost"
>         timeframe = "MonthToDate"
>         dataSet = {
>           granularity = "Daily"
>         }
>       }
>       schedule = {
>         status     = "Active"
>         recurrence = "Daily"
>         recurrencePeriod = {
>           from = time_static.export_start.rfc3339
>           to   = "2099-01-01T00:00:00Z"
>         }
>       }
>       format                = "Parquet"
>       partitionData         = true
>       dataOverwriteBehavior = "OverwritePreviousReport"
>       deliveryInfo = {
>         destination = {
>           container      = azurerm_storage_container.billing.name
>           resourceId     = azurerm_storage_account.cost_exports.id
>           rootFolderPath = "actuals"
>         }
>       }
>     }
>   }
> }
>
> resource "azapi_resource" "amortized" {
>   type      = "Microsoft.CostManagement/exports@2025-03-01"
>   name      = local.amortized_export_name
>   parent_id = "/subscriptions/${var.subscription_id}"
>
>   body = {
>     properties = {
>       definition = {
>         type      = "AmortizedCost"
>         timeframe = "MonthToDate"
>         dataSet = {
>           granularity = "Daily"
>         }
>       }
>       schedule = {
>         status     = "Active"
>         recurrence = "Daily"
>         recurrencePeriod = {
>           from = time_static.export_start.rfc3339
>           to   = "2099-01-01T00:00:00Z"
>         }
>       }
>       format                = "Parquet"
>       partitionData         = true
>       dataOverwriteBehavior = "OverwritePreviousReport"
>       deliveryInfo = {
>         destination = {
>           container      = azurerm_storage_container.billing.name
>           resourceId     = azurerm_storage_account.cost_exports.id
>           rootFolderPath = "amortized"
>         }
>       }
>     }
>   }
> }
>
> locals {
>   absolute_month = tonumber(formatdate("YYYY", plantimestamp())) * 12 + tonumber(formatdate("M", plantimestamp())) - 1
>
>   backfill_months = [
>     for i in range(1, var.backfill_month_count + 1) : format(
>       "%04d-%02d",
>       floor((local.absolute_month - i) / 12),
>       (local.absolute_month - i) % 12 + 1,
>     )
>   ]
>
>   backfill_ranges = {
>     for m in local.backfill_months : m => {
>       from = "${m}-01T00:00:00Z"
>       to = "${formatdate(
>         "YYYY-MM-DD",
>         timeadd(
>           format(
>             "%04d-%02d-01T00:00:00Z",
>             tonumber(split("-", m)[1]) == 12 ? tonumber(split("-", m)[0]) + 1 : tonumber(split("-", m)[0]),
>             tonumber(split("-", m)[1]) == 12 ? 1 : tonumber(split("-", m)[1]) + 1,
>           ),
>           "-24h",
>         ),
>       )}T00:00:00Z"
>     }
>   }
> }
>
> resource "azapi_resource_action" "backfill_actuals" {
>   for_each = var.run_backfill ? local.backfill_ranges : {}
>
>   type        = "Microsoft.CostManagement/exports@2025-03-01"
>   resource_id = azapi_resource.actuals.id
>   action      = "run"
>   method      = "POST"
>   when        = "apply"
>
>   body = {
>     timePeriod = {
>       from = each.value.from
>       to   = each.value.to
>     }
>   }
> }
>
> resource "azapi_resource_action" "backfill_amortized" {
>   for_each = var.run_backfill ? local.backfill_ranges : {}
>
>   type        = "Microsoft.CostManagement/exports@2025-03-01"
>   resource_id = azapi_resource.amortized.id
>   action      = "run"
>   method      = "POST"
>   when        = "apply"
>
>   body = {
>     timePeriod = {
>       from = each.value.from
>       to   = each.value.to
>     }
>   }
> }
>
> resource "azuread_application" "costory" {
>   display_name = "costory-billing-export"
> }
>
> resource "azuread_service_principal" "costory" {
>   client_id = azuread_application.costory.client_id
> }
>
> resource "azuread_application_federated_identity_credential" "costory" {
>   application_id = azuread_application.costory.id
>   display_name   = "costory-gcp"
>   audiences      = ["api://AzureADTokenExchange"]
>   issuer         = "https://accounts.google.com"
>   subject        = data.costory_service_account.current.sub_ids[0]
> }
>
> resource "azurerm_role_assignment" "blob_reader" {
>   scope                = "${azurerm_storage_account.cost_exports.id}/blobServices/default/containers/${azurerm_storage_container.billing.name}"
>   role_definition_name = "Storage Blob Data Reader"
>   principal_id         = azuread_service_principal.costory.object_id
> }
>
> resource "costory_billing_datasource_azure" "main" {
>   name                 = "Azure Production"
>   client_id            = azuread_application.costory.client_id
>   tenant_id            = data.azurerm_client_config.current.tenant_id
>   storage_account_name = azurerm_storage_account.cost_exports.name
>   container_name       = azurerm_storage_container.billing.name
>   actuals_path         = "actuals/${local.actuals_export_name}"
>   amortized_path       = "amortized/${local.amortized_export_name}"
>
>   depends_on = [azurerm_role_assignment.blob_reader]
> }
>
> output "storage_account_name" {
>   value = azurerm_storage_account.cost_exports.name
> }
>
> output "storage_container_name" {
>   value = azurerm_storage_container.billing.name
> }
>
> output "client_id" {
>   value = azuread_application.costory.client_id
> }
>
> output "tenant_id" {
>   value = data.azurerm_client_config.current.tenant_id
> }
> ```
>
> You can also create the Azure AD app and role with Terraform, then paste **Azure client ID** and **Azure tenant ID** in **Connect Azure**.
>
> **Overwrite previous reports**
>
> Set `dataOverwriteBehavior = "OverwritePreviousReport"` on both exports. In the Azure portal this is the **Overwrite data** checkbox, enabled by default on new exports.
>
> If you omit the field, the API applies `CreateNewReport` and each daily run creates a new folder. A datasource references one ActualCost path and one AmortizedCost path. Prefix lists and wildcards are not supported.
>
> Point `actuals_path` and `amortized_path` at the export root folders (`actuals/<export-name>` and `amortized/<export-name>` in the template). With overwrite enabled, each month directory holds only the latest run.
>
> > [!NOTE]
> >
> > If an existing export already created one folder per day, add the overwrite setting, then delete the leftover run folders.
>
> **Choose the Azure scope**
>
> The example above creates the export on a subscription. The same resource works at other Azure scopes. Change `parent_id` on both `azapi_resource` blocks:
>
> ```hcl theme={null}
> resource "azapi_resource" "actuals" {
>   type      = "Microsoft.CostManagement/exports@2025-03-01"
>   name      = local.actuals_export_name
>
>   # Billing Account (recommended)
>   parent_id = "/providers/Microsoft.Billing/billingAccounts/${var.billing_account_id}"
>
>   # Billing Profile (MCA contract)
>   # parent_id = "/providers/Microsoft.Billing/billingAccounts/${var.billing_account_id}/billingProfiles/${var.billing_profile_id}"
>
>   # Management Group
>   # parent_id = "/providers/Microsoft.Management/managementGroups/${var.management_group_id}"
>
>   # Subscription
>   # parent_id = "/subscriptions/${var.subscription_id}"
>
>   # Resource Group
>   # parent_id = "/subscriptions/${var.subscription_id}/resourceGroups/${var.resource_group_name}"
>
>   body = {
>     properties = {
>       # same definition, schedule, format, partitionData, dataOverwriteBehavior, deliveryInfo
>     }
>   }
> }
> ```
>
> If you move the export to another scope, update `actuals_path` and `amortized_path` to the new folder names. Costory still accepts only one prefix per cost type.
>
> **Backfilling historical data**
>
> Azure exports only produce data going forward. To import past months, the module triggers one-off export runs via `azapi_resource_action`. Two variables control this:
>
> | Variable | Default | Description |
> | - | - | - |
> | `backfill_month_count` | `12` | Number of past months to export. |
> | `run_backfill` | `false` | Set to `true` to trigger the backfill runs. |
>
> Run the backfill as a separate apply:
>
> ```bash theme={null}
> terraform apply -var='run_backfill=true'
> ```
>
> This calls the Azure `exports/run` API for both the actuals and amortized exports, one calendar month at a time. Azure writes the Parquet files to the same container and Costory picks them up on the next sync. Set `run_backfill` back to `false` afterward to avoid re-triggering on future applies.

> [tab] Manual setup
>
> In Costory, go to **Billing > Import new billing datasource > Azure** (**Connect Azure**) and follow the stepper.
>
> **Prepare Cost Management exports**
>
> Keep existing exports if you already have them. Costory needs two daily Parquet exports in one storage account / container:
>
> 1. Navigate to **Azure Cost Management > Exports**.
>
> 2. Create two exports using the **Cost and Usage** template: one for **Actual Cost** and one for **Amortized Cost (Spreads upfront commitment payments evenly across the commitment period.)**. Set both to **Daily** recurrence. Leave **Overwrite data** enabled (the default on new portal exports).
>
> 3. Configure a storage account and container as the export destination. Storage account names must be 3-24 lowercase letters or numbers.
>
> 4. Trigger an immediate export run for both exports.
>
> > [!NOTE]
> >
> > A datasource references one ActualCost path and one AmortizedCost path. Prefix lists and wildcards are not supported.
>
> **Grant Costory read access**
>
> In **Connect Azure**, copy the **Google service account unique ID**. Then create an Azure AD app with a federated credential and grant **Storage Blob Data Reader** on the export container. Use the in-app snippet (it already fills the unique ID) or the blocks below.
>
> The federated credential must match exactly:
>
> | Field | Value |
> | - | - |
> | Issuer | `https://accounts.google.com` |
> | Subject | Costory Google SA unique ID (shown in **Connect Azure**) |
> | Audience | `api://AzureADTokenExchange` |
> | Scenario | Other issuer |
> | Role | Storage Blob Data Reader, scoped to the export container |
>
> > [tab] Azure CLI
> >
> > Creates the app, federated credential, and container-scoped role, then prints Client ID / Tenant ID.
> >
> > ```bash theme={null}
> > GOOGLE_SA_UNIQUE_ID="<paste from Connect Azure>"
> > RESOURCE_GROUP="<resource-group>"
> > STORAGE_ACCOUNT="<storage-account>"
> > CONTAINER="<container>"
> >
> > APP_ID=$(az ad app create --display-name "costory-billing-export" --query appId -o tsv)
> > az ad sp create --id "$APP_ID"
> >
> > az ad app federated-credential create --id "$APP_ID" --parameters "{
> >   \"name\": \"costory-gcp\",
> >   \"issuer\": \"https://accounts.google.com\",
> >   \"subject\": \"$GOOGLE_SA_UNIQUE_ID\",
> >   \"audiences\": [\"api://AzureADTokenExchange\"]
> > }"
> >
> > SCOPE=$(az storage account show --name "$STORAGE_ACCOUNT" --resource-group "$RESOURCE_GROUP" --query id -o tsv)
> > az role assignment create \
> >   --role "Storage Blob Data Reader" \
> >   --assignee "$APP_ID" \
> >   --scope "${SCOPE}/blobServices/default/containers/${CONTAINER}"
> >
> > echo "Azure client ID: $APP_ID"
> > echo "Azure tenant ID: $(az account show --query tenantId -o tsv)"
> > ```
>
> > [tab] Terraform
> >
> > Pasteable block. Supply the resource group that owns the storage account. Outputs `client_id` and `tenant_id`.
> >
> > ```hcl theme={null}
> > variable "resource_group_name" {
> >   type        = string
> >   description = "Resource group that owns the storage account"
> > }
> >
> > variable "storage_account_name" {
> >   type        = string
> >   description = "Storage account that holds Cost Management exports"
> > }
> >
> > variable "container_name" {
> >   type        = string
> >   description = "Container that holds Cost Management exports"
> > }
> >
> > variable "google_sa_unique_id" {
> >   type        = string
> >   description = "Costory Google service account unique ID from Connect Azure"
> > }
> >
> > data "azurerm_client_config" "current" {}
> >
> > data "azurerm_storage_account" "exports" {
> >   name                = var.storage_account_name
> >   resource_group_name = var.resource_group_name
> > }
> >
> > resource "azuread_application" "costory" {
> >   display_name = "costory-billing-export"
> > }
> >
> > resource "azuread_service_principal" "costory" {
> >   client_id = azuread_application.costory.client_id
> > }
> >
> > resource "azuread_application_federated_identity_credential" "costory" {
> >   application_id = azuread_application.costory.id
> >   display_name   = "costory-gcp"
> >   audiences      = ["api://AzureADTokenExchange"]
> >   issuer         = "https://accounts.google.com"
> >   subject        = var.google_sa_unique_id
> > }
> >
> > resource "azurerm_role_assignment" "blob_reader" {
> >   scope                = "${data.azurerm_storage_account.exports.id}/blobServices/default/containers/${var.container_name}"
> >   role_definition_name = "Storage Blob Data Reader"
> >   principal_id         = azuread_service_principal.costory.object_id
> > }
> >
> > output "client_id" {
> >   value = azuread_application.costory.client_id
> > }
> >
> > output "tenant_id" {
> >   value = data.azurerm_client_config.current.tenant_id
> > }
> > ```
> >
> > Add the `azurerm` and `azuread` providers if your configuration does not already declare them.
>
> Portal fallback: **App registrations**, then **Federated credentials**, then **Other issuer**, using the table above.
>
> **Connect in Costory**
>
> 1. Paste **Azure client ID** and **Azure tenant ID**.
>
> 2. Select **Detect**, confirm the Actual and Amortized prefixes, then **Validate** and **Save**. There is no SAS field.
>
> > [!NOTE]
> >
> > Role assignment can take a few minutes. If **Validate** fails with credentials or access denied, wait and retry.
>
> > [!NOTE]
> >
> > To backfill historical data, use **Export selected dates** in the Azure portal in 1-month chunks (up to 13 months). Terraform `run_backfill=true` still handles historical backfill if you created the exports with the example above.

## Existing SAS connections

Do not recreate the datasource. Billing history stays.

If the connection still uses a SAS token:

* **Update credentials** still rotates a SAS token until you switch.
* **Switch to federated identity** (Integrations three-dot menu, admin) uses the same CLI or Terraform snippets. Paste **Azure client ID** and **Azure tenant ID**. Costory patches the existing Storage Transfer job in place (same GCS destination). If the first transfer does not start, use **Refresh**. The switch still succeeded.
* After a successful switch, SAS rotation and **Switch to federated identity** disappear. Changing the Azure app later is not a rotate flow.

Google documents the same federated identity pattern for Storage Transfer in [Configure access to a source: Microsoft Azure Storage](https://docs.cloud.google.com/storage-transfer/docs/source-microsoft-azure#user-managed-service-account).

## Related

> [card] [Billing Data](https://docs.costory.io/setup/billing)
>
> All billing providers, backfill, and permissions.

> [card] [Terraform setup](https://docs.costory.io/setup/terraform.md)
>
> Install the Costory provider and authenticate with an API token.

> [card] [AWS billing](https://docs.costory.io/setup/billing/aws.md)
>
> The same Google service account unique ID trusts an IAM role for CUR.

> [card] [Security](https://docs.costory.io/docs/security)
>
> Read-only access. Costory never writes to your cloud accounts.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.