Post
PT EN

FinOps in the Pull Request: Estimating Cloud Costs with Infracost Before Apply

FinOps in the Pull Request: Estimating Cloud Costs with Infracost Before Apply

Introduction

In building Continuous Integration (CI) pipelines for Infrastructure as Code (IaC), the industry standard has established three validation pillars before a terraform apply:

  1. Syntax and Style Validation: terraform fmt and terraform validate.
  2. Static Security Analysis (SAST): Tools like tfsec or checkov.
  3. State Intent Validation: The output of terraform plan.

However, there is a critical absence of financial telemetry. The terraform plan details state mutations and network topologies, but fails to translate these abstractions (e.g., changing iops from 3000 to 10000 on an aws_db_instance) into direct financial impact.

This relegates cost governance to reactive post-deploy auditing processes. To achieve real financial “Shift-Left”, cost estimation must be deterministic and coupled to the Code Review process. This is exactly the architectural layer that Infracost provides.

Infracost Architecture and Operation

Infracost is not a mere static parser. It acts as a SKU resolution engine integrated with your declarative topology. The execution cycle occurs as follows:

  1. Plan Ingestion: Infracost consumes the output of terraform plan converted into a structured JSON format (terraform show -json).
  2. Resource Mapping: The internal engine maps HCL provider resources (e.g., aws_instance) to the Cloud Pricing API taxonomy.
  3. Diff Calculation: The system not only evaluates the total cost, but calculates the delta (difference) between the current state (prior_state) and the planned state (planned_values), generating a precise financial diff.

CI/CD Pipeline Implementation

Injecting Infracost into the pipeline should not block the standard technical pipeline, but run in parallel as an analytical validation job.

Below is the implementation anatomy in a GitHub Actions environment focused on providing visibility in the Pull Request:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
name: IaC Pipeline - Cost Estimation

on:
  pull_request:
    paths:
      - '**/*.tf'

jobs:
  cost-estimation:
    runs-on: ubuntu-latest
    steps:
      - name: Checkout repository
        uses: actions/checkout@v3

      - name: Setup Terraform
        uses: hashicorp/setup-terraform@v2
        with:
          terraform_wrapper: false

      - name: Setup Infracost
        uses: infracost/actions/setup@v2
        with:
          api-key: $

      - name: Generate Terraform Plan
        run: |
          terraform init
          terraform plan -out tfplan.binary
          terraform show -json tfplan.binary > plan.json

      - name: Generate Cost Breakdown
        run: infracost breakdown --path plan.json --format json --out-file infracost.json

      - name: Notify Pull Request
        uses: infracost/actions/comment@v2
        with:
          path: infracost.json
          behavior: update

Active Governance: Integrating Infracost and OPA (Open Policy Agent)

Financial visibility is the first step. The final maturity stage in Platform Engineering requires Policy as Code.

Since Infracost exports the estimate as structured JSON, we can couple Open Policy Agent (OPA) to apply Hard Guardrails. Instead of relying on human judgment to approve a cost surge, we define deterministic rules using the Rego language.

Example Rego Policy for FinOps

Consider an engineering directive: No Pull Request can introduce a monthly cost increase of more than $500 without explicit approval.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
package terraform.finops

import input as infracost_data

# Define the blocking rule
deny[msg] {
    # Extract the financial delta from the JSON generated by Infracost
    monthly_diff := to_number(infracost_data.diffTotalMonthlyCost)
    
    # Violation condition
    monthly_diff > 500
    
    # Error formatting for the CI/CD stdout
    msg := sprintf("BLOCKED BY FINOPS: The projected cost increment ($%.2f) exceeds the established limit of $500.00 per PR.", [monthly_diff])
}

By adding an opa eval step to the pipeline right after Infracost runs, the pipeline will intentionally fail (Exit Code 1) if the condition is met.

Conclusion

Integrating Infracost transforms cloud cost management from a lagging accounting process into a rigorous engineering metric, treated with the same seriousness as test coverage and vulnerability analysis.

By unifying Infracost with Open Policy Agent in the CI/CD pipeline, organizations eliminate inadvertent provisioning of expensive resources. This architecture ensures that cloud platforms scale under deterministic governance, merging the interests of technical scalability with financial accountability directly at the root of the infrastructure repository.

This post is licensed under CC BY 4.0 by the author.