123DevOps··5 min read

Shift-left cost governance: Infracost in the Pull Request blocking spend before deploy

How to show the cost estimate of every Terraform change in the PR, block increases above a threshold, require tags with policy as code and create an approval process that doesn't slow the team down.

FinOps

At most companies, the cost cycle works like this: the engineer deploys, the resource runs for weeks, the bill arrives, someone in finance asks “what is this?” and an investigation begins to figure out who created what. By the time the problem is found, the money has already been spent.

Shift-left cost management reverses that order: the question “how much will this cost?” is answered in the Pull Request, before the merge — in the same place and at the same moment the team already reviews security and code quality.

How Infracost works

Infracost reads infrastructure code (Terraform/OpenTofu, as well as Terragrunt and other formats), identifies the resources and queries a pricing database from the cloud providers to estimate the monthly cost. Locally:

infracost auth login                    # generates the free API key
infracost breakdown --path=infra        # estimated cost of the current code
infracost diff --path=infra             # difference compared to the previous state

A typical diff output shows something like “+ $1,240/month” and breaks down the reason: the database instance changed size, a NAT Gateway was added, the volume went from 100 to 2,000 GB.

In the Pull Request with GitHub Actions

The recommended flow calculates the cost of the base branch, then the cost of the PR branch, and posts the difference as a comment:

name: infracost
on:
  pull_request:
    paths: ["infra/**"]

permissions:
  contents: read
  pull-requests: write

jobs:
  cost:
    runs-on: ubuntu-latest
    steps:
      - name: Check out the base branch
        uses: actions/checkout@v4
        with:
          ref: ${{ github.event.pull_request.base.ref }}

      - uses: infracost/actions/setup@v3
        with:
          api-key: ${{ secrets.INFRACOST_API_KEY }}

      - name: Base branch cost
        run: infracost breakdown --path=infra --format=json --out-file=/tmp/base.json

      - name: Check out the PR
        uses: actions/checkout@v4

      - name: PR cost difference
        run: infracost diff --path=infra --compare-to=/tmp/base.json --format=json --out-file=/tmp/diff.json

      - name: Comment on the PR
        run: |
          infracost comment github --path=/tmp/diff.json \
            --repo="$GITHUB_REPOSITORY" \
            --github-token="${{ github.token }}" \
            --pull-request="${{ github.event.pull_request.number }}" \
            --behavior=update

      - name: Block increases above the threshold
        run: |
          INCREASE=$(jq -r '.diffTotalMonthlyCost // "0"' /tmp/diff.json)
          echo "Estimated monthly increase: \$${INCREASE}"
          if awk -v a="$INCREASE" 'BEGIN { exit !(a > 500) }'; then
            echo "::error::Estimated increase above \$500/month — requires FinOps approval"
            exit 1
          fi

With --behavior=update, Infracost edits the same comment on every new commit instead of cluttering the PR.

Turning visibility into governance

Showing the cost already changes behavior — engineers rarely want to be “the $5,000 PR”. But for it to become governance, the check needs to have consequences:

  1. Mark the infracost job as a required check in the main branch protection rules.
  2. Define per-environment thresholds: small increases in development go straight through; in production, the threshold is lower and requires approval.
  3. Create a clear exception path: a label (e.g., finops-approved) that only the FinOps team or the tech lead can apply, or a CODEOWNERS file that requires review from someone in FinOps when the check fails.

The goal isn’t to forbid spending — it’s to make sure large spending is a conscious decision, recorded in the PR, with an owner and a justification.

Policy as code: mandatory tags and standards

Estimated cost is half of governance. The other half is making sure every resource is born allocatable and within standards. With the Terraform plan in JSON and Conftest (which uses OPA’s Rego language), you can block untagged resources:

package main

deny contains msg if {
  rc := input.resource_changes[_]
  rc.change.actions[_] == "create"
  startswith(rc.type, "aws_")
  tags := object.get(rc.change.after, "tags", {})
  not tags.team
  msg := sprintf("%s was created without the required 'team' tag", [rc.address])
}

deny contains msg if {
  rc := input.resource_changes[_]
  rc.type == "aws_ebs_volume"
  rc.change.after.type == "gp2"
  msg := sprintf("%s uses gp2; use gp3 (cheaper and with configurable IOPS)", [rc.address])
}
terraform plan -out=plan.out
terraform show -json plan.out > plan.json
conftest test plan.json

Other rules worth their weight in gold: mandatory retention on log groups, banning very large instance types outside an approved list, lifecycle rules on buckets, and requiring default_tags in the provider.

Limitations you need to know about

  • Usage-based costs (data transfer, serverless function requests, GB processed by a NAT Gateway, storage that grows) don’t show up in the code. Infracost supports an infracost-usage.yml file with usage estimates — use it for the resources where this matters most.
  • Discounts don’t show up by default. Estimates use list prices; negotiated contracts, Savings Plans and credits aren’t included unless you configure custom prices on the tool’s paid plans.
  • Resources outside Terraform (created through the console or by Kubernetes operators) slip through. Shift-left doesn’t replace continuous monitoring for zombie resources.
  • The estimate isn’t the bill. Use it to compare changes and spot jumps, not to forecast the month-end close down to the cent.

Measuring the impact

To show that the process works, track:

  • Estimated monthly increase summed across all PRs merged each month;
  • Blocked PRs, and how many were changed (e.g., a smaller instance) versus approved as exceptions;
  • Percentage of resources with mandatory tags over time;
  • Bill variation not explained by PRs — if it’s large, a lot of resources are being created outside the code workflow.

Where to start

  1. Run Infracost in comment-only mode for a few weeks, without blocking anything. Let the team get used to it.
  2. Add the tagging policies with Conftest and fix the legacy resources gradually.
  3. Agree on the thresholds and the exception flow with FinOps and technical leadership.
  4. Make the check required in production.

The cheapest time to save money in the cloud is before the resource exists. Every PR reviewed with the cost on screen is a surprise bill that will never arrive.

Get updates on new posts and stay in the loop!