Setting up Infracost plan policies with custom data input
Last updated: September 9, 2025
When using Infracost with Spacelift plan policies to monitor cost changes, you need to properly configure both the data collection and policy structure to access cost information.
Required Setup
To use Infracost data in your plan policies, you need:
Set the
INFRACOST_API_KEYenvironment variableAdd the
infracostlabel to your stackAdd a pre-plan hook with the following commands:
infracost breakdown --path . --out-file infracost.custom.spacelift.json --format json
The pre-plan hook is essential for generating the custom data that your policy can access, even though it may not be explicitly mentioned in the Infracost documentation.
Correct Policy Structure
When writing your plan policy to access Infracost data, make sure to include custom in the data path. The correct structure is:
input.third_party_metadata.custom.infracost.projects[0].breakdown.totalMonthlyCost
Here's an example policy snippet that warns when monthly costs exceed a threshold:
warn[sprintf("monthly cost greater than $%d ($%.2f)", [threshold, monthly_cost])] {
threshold := 100
monthly_cost := to_number(input.third_party_metadata.custom.infracost.projects[0].breakdown.totalMonthlyCost)
monthly_cost > threshold
}Testing Your Policy
Use the policy workbench to test your policy. Add sample := true to your policy to see the actual data structure and verify the correct path to your Infracost data.
Policy Behavior with PR Comments
When using deny rules that fail the run, Infracost breakdown information will not appear in GitHub PR comments since the API call is made after a successful plan phase. If you want to see both the cost breakdown and policy warnings in your PR, use warn instead of deny in your policy rules.
Common Error Messages
You may see error messages like "terraform JSON plan is missing the 'format_version' property" in your logs. This is typically a harmless warning and doesn't prevent the policy from working correctly as long as you have the proper setup described above.