In part one we put budgets, allocations, alerts and reports under version control. Part two went deeper on those four and then moved on to the tenant itself, with roles, users and service accounts that have rotating tokens. Three more minor releases (v1.11 to v1.13) have shipped since, and the DoiT Terraform provider now covers 24 resources and 98 data sources.
The first half of this post covers new building blocks: notifications for the whole organization and for single users, scheduled report delivery, custom metrics and time-bound allocation rules. The second half is about data sources. They look things up, guard your plans and export files, and they can read everything you built in the Cloud Intelligence console, so you can bring it under Terraform without rebuilding it.
We ran every snippet below against a real DoiT tenant before it went into this post, and applied, re-planned for drift and destroyed it wherever that was safe. Most of them are also in the provider documentation examples.
Notifications as Code
Alerts, budgets and anomaly detection decide when something is wrong. Notifications decide who hears about it, and where. Three resources cover that now. doit_customer_notification handles rules for the whole organization, doit_user_notification handles the personal subscriptions of one user, and doit_customer_subscription delivers reports, dashboards and commitments on a schedule. All three arrived in v1.12. v1.13 extended organization notifications to every notification type, and added the billing transfer types for users.
Organization-Wide Rules
A customer notification sends cost anomalies, invoices, digests or insights to email, Slack and Microsoft Teams. This rule covers critical anomalies of one allocation and resends while the anomaly keeps growing:
resource "doit_customer_notification" "production_critical" { name = "Critical production anomalies"
destinations = { emails = ["finops@example.com"] slack_channels = ["C0123ABCD"] teams_channels = [] }
settings = { cost_anomalies = { min_severity = "critical" min_excess_cost = { amount = "1000.00", currency = "USD" } allocations = { mode = "include" ids = [doit_allocation.production.id] }
# Resend every 12 hours while the anomaly is active, and whenever its # cost grows by 20% or by $500 within 6 hours. repeat = { every_hours = 12 when_cost_grows = { match = "or" percent_increase = 20 min_increase = { amount = "500.00", currency = "USD" } within_hours = 6 } } } }}Finance needs something different, and no allocations are involved. Setting a type to {} subscribes with its defaults, and billing_profile_ids narrows it to specific billing profiles:
resource "doit_customer_notification" "finance" { name = "Finance: invoices and payments"
destinations = { emails = ["finance@example.com"] slack_channels = [] teams_channels = [] }
settings = { new_invoices = {} new_proforma_invoices = {} payment_reminders = { billing_profile_ids = ["YOUR-BILLING-PROFILE-ID"] } }}These four rules apply to every customer notification:
- Allocation IDs must belong to custom single allocations. Preset, group and managed allocations are rejected, which fits the team allocations from part two.
- All three destination lists are required. Use
[]for the ones you don't use. Email recipients must be users of your organization. - Terraform is authoritative about the types. A notification type that someone adds to a Terraform-managed notification in the Cloud Intelligence console shows up as a change and is removed on the next apply, unless you add it to the configuration.
- Teams doesn't get every type.
expert_insightsanddata_integration_sync_failurecan't be delivered to Teams, and the provider checks that at plan time.
Personal Subscriptions
doit_user_notification manages what one user receives, delivered to that user's own address. To subscribe a group of people, use a for_each over their IDs. One doit_users read finds all of them:
locals { digest_emails = ["jane.doe@example.com", "john.smith@example.com"]}
data "doit_users" "all" {}
locals { digest_users = { for u in data.doit_users.all.users : u.email => u.id if contains(local.digest_emails, u.email) }}
resource "doit_user_notification" "team_digest" { for_each = local.digest_users
user_id = each.value name = "Daily production digest"
settings = { daily_digest = { allocation_ids = [doit_allocation.production.id] } }}Every type except cost anomalies needs the matching permission on the user, for example Cloud Analytics User for digests or Invoice Viewer for invoices. The API checks it on every create and update, and the 403 error names the missing permission. Distributors and resellers also get six billing transfer types (v1.13), like billing_transfer_new_end_customer = {}, which need the Billing Transfer Admin permission.
Scheduled Delivery
Part two ended with a GitHub Actions pipeline that sent a weekly report. If all you need is "email this report every Monday", a subscription does that natively now:
resource "doit_customer_subscription" "finops" { recipients = { emails = ["finops@example.com"] slack_channels = [] }
subscriptions = [{ type = "report-subscription" source = { id = doit_report.monthly_costs.id } schedule = { time_zone = "Europe/Berlin" # The start day is the calendar date of this instant in time_zone. start_date = "2026-11-02T00:00:00+01:00" # Only the hour and minute, read in time_zone, are used. time = "2026-11-02T08:00:00+01:00" frequency = "Weekly" } attachments = ["pdf", "csv"] }]}The same resource delivers dashboards and commitments, and one resource can combine several entries for one set of recipients. Keep the pipeline when you want more than the report, like Ava's summary or a check block in the same run.
Custom Metrics
Cost, usage and savings are the metrics every report starts from. A custom metric (v1.13) is a formula over them, measured on up to five single allocations. This one is the share of Google Cloud in the combined Google Cloud and AWS cost:
resource "doit_custom_metric" "gcp_share" { name = "Google Cloud share" description = "Google Cloud cost as a percentage of Google Cloud and AWS cost" variables = [ { metric = { type = "basic", value = "cost" } allocation_id = doit_allocation.gcp.id }, { metric = { type = "basic", value = "cost" } allocation_id = doit_allocation.aws.id }, ] formula = "A / (A + B) * 100" unit_type = "percentage" decimals = { min = 0, max = 2 }}A variable's position sets its letter, so the first is A and the second is B. A variable can also measure an extended metric like amortized cost. To find its key, look it up by label with the new doit_extended_metrics data source instead of guessing:
data "doit_extended_metrics" "billing" { filter = "dataSource:billing,billing-datahub"}
locals { keys_by_label = { for m in data.doit_extended_metrics.billing.items : m.label => m.key... }}Reports and alerts refer to a custom metric by its ID. This report charts the share per month, and the alert fires when Google Cloud is more than 60% of the combined cost:
resource "doit_report" "gcp_share" { name = "Google Cloud share" config = { metrics = [{ type = "custom", value = doit_custom_metric.gcp_share.id }] aggregation = "total" time_interval = "month" data_source = "billing" dimensions = [{ id = "month", type = "datetime" }] time_range = { mode = "last" amount = 3 include_current = true unit = "month" } }}
resource "doit_alert" "gcp_share" { name = "Google Cloud share above 60%" config = { metric = { type = "custom", value = doit_custom_metric.gcp_share.id } time_interval = "month" condition = "value" operator = "gt" value = 60 currency = "USD" } recipients = [data.doit_current_user.me.email]}Custom metrics need the calculated metrics entitlement. Budgets can't use them, because a budget's metric is cost or amortized_cost.
Time-Bound Allocation Rules
Organizations change, and costs should follow the change on the right date without anyone rewriting history. validity_periods (v1.11) limits the dates on which a single allocation's rule applies. Dates are in UTC and inclusive, so a handover needs a one-day gap: the first allocation ends on the last day, the second starts on the next one.
This moves Payments to a new project on 1 January 2027, and a group selects both so one allocation reports Payments across the handover:
resource "doit_allocation" "payments_old_project" { name = "Payments (old project)" description = "Payments costs until the move" rule = { formula = "A" components = [{ mode = "is" type = "fixed" key = "project_id" values = ["payments-legacy"] }] validity_periods = [{ end_date = "2026-12-31" }] }}
resource "doit_allocation" "payments_new_project" { name = "Payments (new project)" description = "Payments costs after the move" rule = { formula = "A" components = [{ mode = "is" type = "fixed" key = "project_id" values = ["payments"] }] validity_periods = [{ start_date = "2027-01-01" }] }}
resource "doit_allocation" "payments" { name = "Payments" description = "Payments costs before and after the move" unallocated_costs = "Other" rules = [ { action = "select", id = doit_allocation.payments_old_project.id }, { action = "select", id = doit_allocation.payments_new_project.id }, ]}The provider checks the date format, the order and any overlap at plan time. The dates belong to the single allocation's own rule, so they sit on the two singles and not on the group's select rules. The API rejects validity periods on a select rule.
Data Sources at Work
In part one, data sources kept IDs out of your configuration. They can do more. They look things up, they guard your plans, they export files out of DoiT, and they let you adopt what already exists. That last job gets its own section below.
Look Up: Names Instead of IDs
Slack channel IDs are the best example. Notifications, subscriptions and alerts all want an ID, and nobody remembers C0123ABCD. doit_alert_slack_channels lists the channels connected to your organization, so a team can refer to its channel by name:
data "doit_alert_slack_channels" "all" {}
locals { # A shared channel can be listed twice (as shared and as public) with the # same id, so group by name and take the first entry. slack_channel_ids = { for name, ids in { for c in data.doit_alert_slack_channels.all.items : c.name => c.id... } : name => ids[0] }}
output "finops_alerts_channel_id" { value = lookup(local.slack_channel_ids, "finops-alerts", null)}Private channels are never listed for service accounts, so the lookup returns null for them. The data source sets channels_complete to false when the list may be missing channels, so check it before you rely on the lookup. The same pattern works for doit_users (an email to a user ID, as above), doit_extended_metrics (a label to a key) and doit_commitments (the source of a commitment subscription).
Guard: Check Blocks Beyond Budgets
Part two used check blocks for budgets at risk and for service quota headroom. The same trick works for invoices. This one warns on every plan while an invoice is past due, and it never blocks an apply:
check "no_past_due_invoices" { data "doit_invoices" "past_due" { filter = "status:PAST DUE" }
assert { condition = data.doit_invoices.past_due.row_count == 0 error_message = "Past due invoices: ${join(", ", [for inv in data.doit_invoices.past_due.invoices : inv.id])}" }}Only one status value is applied per request, and canceled invoices and credit memos (v1.12) only show up with status:CANCELED. Composer Insights recipes have data sources as well, doit_composer_recipes and doit_composer_recipe_results. They're in beta, so we'll write more about them once they're out of it.
Export: Files Out of DoiT
Invoices and report results can leave DoiT as files without anyone clicking a download button. doit_invoice_pdf returns the PDF base64-encoded, together with its file name:
data "doit_invoice_pdf" "latest" { id = "your-invoice-number"}
resource "local_sensitive_file" "invoice_pdf" { filename = "${path.module}/${data.doit_invoice_pdf.latest.filename}" content_base64 = data.doit_invoice_pdf.latest.content_base64}Swap local_sensitive_file for an aws_s3_object (it takes the same content_base64) and the invoices land in a bucket.
Part two exported reports as PDF and PNG. Since v1.12, file_output also takes csv and json, which you want when the report feeds a data pipeline and not a person:
data "doit_report_result" "costs_csv" { id = doit_report.monthly_costs.id file_output = "csv"
lifecycle { postcondition { condition = self.file_output_url != null error_message = "The report result was available, but CSV rendering failed. Try applying again." } }}
data "http" "costs_csv" { url = data.doit_report_result.costs_csv.file_output_url}
resource "local_sensitive_file" "costs_csv" { filename = "${path.module}/costs.csv" content_base64 = data.http.costs_csv.response_body_base64}Two details matter for whatever reads that file. The CSV starts with a UTF-8 byte-order mark and uses CRLF line endings, so tell your parser. And once a file is rendered, rows is null in result_json and row_count is null too, because the rows are in the file. json returns the whole result as a file, including the secondary and forecast rows that a CSV leaves out, and it's the way to get a result that's too large to return inline.
Adopt What You Built in the Cloud Intelligence
Many Cloud Intelligence setups start in the UI, long before anyone writes Terraform for them. You don't have to rebuild them. Terraform can import an existing object into its state and write the configuration for it, and importing doesn't change anything in DoiT. Every resource in the provider supports import.
One Object
An import block names the object, and Terraform writes the resource for you:
import { to = doit_report.monthly_costs id = "REPORT_ID"}terraform plan -generate-config-out=generated.tfterraform applyterraform plan # No changes. Your infrastructure matches the configuration.This needs Terraform 1.5 or later (1.7 for for_each in import blocks, which comes up below). For an object that follows today's rules, the generated configuration is valid as it is, so you review it and move it into your files. A few attributes only repeat a default, like timeouts = null, and you can delete them. Most resources are imported by their ID. The exceptions are doit_user (the email address), doit_user_notification (user_id/notification_id), doit_service_account_token (service_account_id/token_id) and doit_sharing (reports/abc123def456). The new importing guide has the full list.
Many Objects
A tenant can hold hundreds of budgets, allocations and reports, and writing an import block for each one by hand is not practical. An import block can use for_each, but Terraform can't generate configuration for one and stops with The target resource does not use for_each. So adopting many objects takes two steps. First, a small discovery configuration reads the objects with the list data sources and prints plain import blocks:
variable "name_contains" { type = string default = null}
data "doit_budgets" "all" { name_contains = var.name_contains }data "doit_reports" "all" { name_contains = var.name_contains }
locals { objects = concat( [for b in data.doit_budgets.all.budgets : { type = "doit_budget", name = b.budget_name, id = b.id }], # Preset reports belong to DoiT, so only custom ones are adopted. [for r in data.doit_reports.all.reports : { type = "doit_report", name = r.report_name, id = r.id } if r.type == "custom"], )
# Names aren't unique, so every address ends in the object's ID. import_blocks = [ for o in local.objects : "import {\n to = ${o.type}.${trimprefix(o.type, "doit_")}_${substr(replace(lower(o.name), "/[^a-z0-9]+/", "_"), 0, 40)}_${o.id}\n id = \"${o.id}\"\n}\n" ]}
output "import_blocks" { value = join("\n", local.import_blocks)}The guide's version also reads allocations and alerts. Run it once, write the blocks into your real configuration, and let Terraform generate the resources:
terraform apply -var name_contains=paymentsterraform output -raw import_blocks > ../adopt/imports.tf
cd ../adoptterraform plan -generate-config-out=generated.tfterraform applyAdopt one team or project at a time with name_contains, not the whole tenant at once. The generated configuration goes through the same validation as configuration you write by hand, so an old object that breaks today's rules fails the plan, and one invalid resource fails all of it. On our test tenant, that was a group allocation without unallocated_costs and a budget with a start_period of 0, among others. The error names the resource, and the guide shows how to fix it or leave it out.
From Generated to Idiomatic
Generated resources are flat, with one block per object and the ID in its address. If your objects follow a pattern, like one allocation per team, collapse them into a for_each map like the one from part two, and let moved blocks tell Terraform that the new address is the same object:
locals { teams = { gcp = { cloud = "google-cloud" } aws = { cloud = "amazon-web-services" } }}
resource "doit_allocation" "team" { for_each = local.teams name = "Team ${each.key}" description = "All ${each.value.cloud} costs" rule = { formula = "A" components = [{ key = "cloud_provider" mode = "is" type = "fixed" values = [each.value.cloud] }] }}
# One moved block per object.moved { from = doit_allocation.allocation_team_gcp_AbC123 to = doit_allocation.team["gcp"]}terraform plan reports has moved to doit_allocation.team["gcp"] and nothing else. No object is recreated and nothing is sent to DoiT. If the plan also shows an update, the new configuration doesn't match the object yet.
Three more cases to watch for:
- Groups. A group allocation's members are ordinary single allocations, however each one was created. The API doesn't return how, so an imported group always comes back with
selectrules that point at its members by ID. Import the members as their own resources and replace the literal IDs with references. - Secrets. An imported service account token has no
access_token, because the API returns the secret only when the token is created. A pipeline that needs the secret needs a new token. - Taking it back. A
removedblock withdestroy = falsestops managing an object without deleting it.
Cloud bill shouldn't be a mystery
One platform for AI and Cloud optimization.
Putting It Together: Onboard a Team with One Map Entry
In part two, a map of teams produced an allocation, a budget and an alert for each of them. Here, a similar map gives each team its own allocation, a share-of-spend metric and report, a weekly report in its Slack channel and a notification for critical anomalies:
locals { teams = { payments = { label = "payments" # value of the "owner" label on the team's costs slack_channel = "payments-finops" # name of a Slack channel connected to DoiT lead = "ana@example.com" # a user of your DoiT organization } search = { label = "search" slack_channel = "search-finops" lead = "ravi@example.com" } }}The share metric needs a denominator. A custom metric can have only five variables, so instead of adding up the teams, one allocation matches all spend. "Is not none" matches every cost row, because no row has none as its cloud provider. On our test tenant, a metric on this allocation matched the plain report total for three months exactly:
resource "doit_allocation" "total" { name = "All cloud spend" description = "Every cost row" rule = { formula = "A" components = [{ type = "fixed" key = "cloud_provider" mode = "is" inverse = true values = ["none"] }] }}
resource "doit_custom_metric" "team_share" { for_each = local.teams
name = "Share of spend: ${each.key}" variables = [ { metric = { type = "basic", value = "cost" } allocation_id = doit_allocation.team[each.key].id }, { metric = { type = "basic", value = "cost" } allocation_id = doit_allocation.total.id }, ] formula = "A / B * 100" unit_type = "percentage" decimals = { min = 0, max = 1 }}The team allocations are the ones from part two (one single allocation per team, with anomaly detection), and the report on the share metric looks like the one in the custom metrics section, once per team. local.slack_channel_ids is the lookup from the data sources section, and local.user_emails is [for u in data.doit_users.all.users : lower(u.email)]. The delivery resources use both, and they check the map before anything is created, so a typo fails the plan with a readable message instead of an API error at apply:
resource "doit_customer_notification" "team_critical" { for_each = local.teams
name = "Team ${each.key}: critical cost anomalies"
destinations = { emails = [each.value.lead] slack_channels = [local.slack_channel_ids[each.value.slack_channel]] teams_channels = [] }
settings = { cost_anomalies = { min_severity = "critical" min_excess_cost = { amount = "100.00", currency = "USD" } allocations = { mode = "include" ids = [doit_allocation.team[each.key].id] } } }
lifecycle { precondition { condition = contains(keys(local.slack_channel_ids), each.value.slack_channel) error_message = "Team ${each.key}: the Slack channel \"${each.value.slack_channel}\" is not connected to DoiT." } precondition { condition = contains(local.user_emails, lower(each.value.lead)) error_message = "Team ${each.key}: ${each.value.lead} is not a user of this DoiT organization." } }}The weekly report delivery has the same shape, with a doit_customer_subscription in place of the notification. On a test tenant, two teams created 11 resources. A third entry in the map planned five new resources and nothing else, and removing it planned exactly those five destroys. Teams you adopted from the Cloud Intelligence can join the same map with moved blocks. The complete configuration is in the repository.
Quick Hits
Some smaller additions:
- Seasonal budgets.
seasonal_amountssets a different amount for each period (v1.13), for example twelve amounts for a monthly budget.allow_growthandrolloverare new as well, andcurrent_period_amountshows the amount of the current period. The upgrade table below has the one breaking change. - Report display options.
show_data_labels,logarithmic_scaleandshow_totals_panelare new indisplay_settings. You can now removecount,custom_time_range,limit_by_changeandmetric_filterfrom a report in place instead of replacing the report. - Attribute.
data_source = "attribution"with the newattribution_tier_1toattribution_tier_3dimensions letsdoit_report_queryread DoiT Attribute attributions. It requires an Attribute subscription. - Anomalies.
doit_anomalyexposescustomer_feedback, including the resolution note, and bothdoit_anomalyanddoit_anomaliesexposeinitial_notifications. - Assets.
doit_assetanddoit_assetshave asupportobject with the vendor support model and tier of AWS and Google Cloud assets. It isnullwhen the API doesn't return it, which doesn't mean the asset has no support.
Upgrading from v1.10
The snippets above need v1.13, so if you're on v1.10 or earlier, upgrade first. These changes can affect an existing configuration:
| Version | Change | What to do |
|---|---|---|
| v1.11 | doit_dimensions: sort_by = "timestamp" removed |
Sort by another value, such as id |
| v1.11 | Destroying a group, or removing one of its create rules, now also deletes the single allocation that rule made. Before, it stayed behind |
Nothing, unless you relied on the leftover allocations |
| v1.12 | doit_support_request_comments: comments[].id is a string |
Compare and format it as a string |
| v1.12 | With file_output set, rows is null in result_json and row_count is null |
Read the file, or drop file_output |
| v1.12 | doit_ps4c_commitment_policy(ies): ladder_interval_days removed |
Drop the reference (steps are always 7 days apart) |
| v1.12 | Stricter checks at plan time, for example name and scopes of a budget must not be empty and a collaborator needs a role |
Fix what the plan reports. Nothing is sent to the API |
| v1.12 | When data_source is omitted on create, the API picks billing-datahub for tenants with DataHub metrics, and billing otherwise |
Set data_source to pin it |
| v1.13 | A budget with seasonal_amounts has no amount, and omitting seasonal_amounts removes them |
Remove amount from seasonal budgets, and set amount or use_prev_spend otherwise |
The changelog has every detail.
Wrapping Up
Notifications, custom metrics and time-bound rules are configuration now, like everything else in this series, so a pull request can review them. Data sources do the rest of the work. They look things up, guard your plans, export files and read everything that already exists. The adoption flow is the easiest part to try today: run the discovery configuration with name_contains for one team and see what Terraform writes for you.
Upgrade to v1.13 first, and check the table above. Then add a notification for the anomalies of your most important allocation, and watch the repository's releases (Watch → Custom → Releases).
The provider is open source at github.com/doitintl/terraform-provider-doit, and the documentation has most of the examples from this post, and many more. If something's missing or awkward, open an issue and tell us.