Tutorial
A Step-by-Step Guide to Showing Terraform Costs in GitHub Pull Requests with Infracost
Want to see cloud cost estimates right in your GitHub pull requests? This easy-to-follow guide walks you through setting up Infracost with GitHub Actions step-by-step. You'll learn how to automate cost feedback, making it simple for your team to catch expensive changes before they ever go live.
A Step-by-Step Guide to Showing Terraform Costs in GitHub Pull Requests with Infracost

One of the most powerful ways to control cloud costs is to make them visible during the development process. When engineers can see the financial impact of their infrastructure changes before they merge their code, they are empowered to make smarter, more cost-effective decisions. Infracost, combined with GitHub Actions, provides a seamless way to automate this process, posting clear cost estimates directly as comments in your Terraform pull requests.

This guide provides a step-by-step process for setting up Infracost with GitHub Actions to bring proactive cost visibility into your workflow.

The Two Integration Methods: GitHub App vs. GitHub Action

Before diving into the setup, it's important to understand the two primary ways to integrate Infracost with GitHub:

  1. The Infracost GitHub App (Recommended): This is the simplest and fastest way to get started. The app handles most of the configuration automatically. You install it on your organization or repository, grant it permissions, and it starts commenting on pull requests without requiring you to write a complex workflow file. It runs on Infracost's infrastructure, which can be faster than waiting for a GitHub Actions runner.

  2. The Infracost GitHub Action: This method gives you more granular control over the workflow. You define the exact steps Infracost will run within your own .github/workflows/infracost.yml file. This is useful for complex setups, such as those involving private modules or custom scripting, but requires more manual configuration.

While the GitHub App is recommended for its simplicity, this guide will focus on the GitHub Action setup, as it provides a clearer understanding of the underlying mechanics. The principles are the same for both.

Step 1: Get Your Infracost API Key

Infracost requires a free API key to fetch cloud pricing data and to post comments to pull requests. This key does not grant any access to your cloud accounts.

  1. Install the Infracost CLI: If you don't have it already, install the Infracost CLI on your local machine. The quickest way is via their install script:

    Shell

    curl -fsSL https://raw.githubusercontent.com/infracost/infracost/master/scripts/install.sh | sh
    
  2. Authenticate and Register: Run the login command. This will open a browser window for you to authenticate with your GitHub or Google account and generate an API key.

    Shell

    infracost auth login
    
  3. Retrieve Your API Key: Once authenticated, retrieve the key from your local configuration so you can add it to GitHub.

    Shell

    infracost configure get api_key
    

    Copy the output of this command.

Step 2: Add the API Key to GitHub Secrets

To use your API key securely within GitHub Actions, you must store it as an encrypted secret in your repository.

  1. Navigate to your GitHub repository and go to Settings > Secrets and variables > Actions.

  2. Click New repository secret.

  3. Name the secret INFRACOST_API_KEY.

  4. Paste the API key you copied in the previous step into the Secret value box.

  5. Click Add secret.

Step 3: Create the GitHub Actions Workflow File

Now, you will create the YAML file that defines the CI/CD workflow for Infracost.

  1. In your repository, create a new file at the path .github/workflows/infracost.yml.

  2. Paste the following workflow configuration into the file. This is a standard workflow provided by Infracost that covers the most common use case.

YAML

name: Infracost
on:
  pull_request:
    types: [opened, synchronize]
permissions:
  contents: read
  pull-requests: write
jobs:
  infracost:
    name: Infracost
    runs-on: ubuntu-latest
    steps:
      - name: Setup Infracost
        uses: infracost/actions/setup@v3
        with:
          api-key: ${{ secrets.INFRACOST_API_KEY }}

      - name: Checkout base branch
        uses: actions/checkout@v4
        with:
          ref: ${{ github.event.pull_request.base.ref }}

      - name: Generate Infracost baseline
        run: |
          infracost breakdown --path=. \
                            --format=json \
                            --out-file=/tmp/infracost-base.json

      - name: Checkout PR branch
        uses: actions/checkout@v4

      - name: Generate Infracost diff
        run: |
          infracost diff --path=. \
                         --format=json \
                         --compare-to=/tmp/infracost-base.json \
                         --out-file=/tmp/infracost.json

      - name: Post Infracost comment
        run: |
          infracost comment github --path=/tmp/infracost.json \
                                   --repo=$GITHUB_REPOSITORY \
                                   --github-token=${{ github.token }} \
                                   --pull-request=${{ github.event.pull_request.number }} \
                                   --behavior=update

Understanding the Workflow Steps

This workflow is triggered whenever a pull request is opened or updated. Let's break down what each step does:

  • Permissions: The pull-requests: write permission is crucial. It allows the action to post comments on your behalf using the default github.token. Without this, the final step will fail.

  • Setup Infracost: This step uses a pre-built Infracost action to install the CLI and configure it with your API key from GitHub Secrets.

  • Checkout base branch: The workflow first checks out the base branch of the pull request (e.g., main). This is necessary to create a "before" snapshot of your infrastructure's cost.

  • Generate Infracost baseline: It runs infracost breakdown on the base branch code and saves the JSON output to a file. This file serves as the cost baseline.

  • Checkout PR branch: Next, it checks out the code from the pull request branch itself—the "after" state.

  • Generate Infracost diff: It runs infracost diff, comparing the current code against the baseline file. This command calculates the cost difference and saves it to a new JSON file.

  • Post Infracost comment: This final step uses the infracost comment command to post the results to the pull request. The --behavior=update flag is the quietest option; it creates a single comment and updates it with new information on subsequent pushes, avoiding clutter.

Step 4: Test the Integration

With the workflow file committed to your repository, the setup is complete. To test it:

  1. Create a new branch in your repository.

  2. Make a change to a Terraform file that affects cost. For example, change an AWS EC2 instance type from t3.micro to t3.large.

  3. Commit the change and open a pull request.

Within a minute or two, the "Infracost" action will run. Once it completes, you will see a new comment on your pull request from the Infracost bot, detailing the estimated monthly cost change, just like the one shown in the documentation.

Advanced Configuration Options

The provided workflow is a great starting point, but the GitHub Action offers flexibility for more complex scenarios:

  • Private Modules: If your Terraform configuration uses private Git modules, you'll need to provide an SSH key to the workflow so Infracost can access them. This typically involves adding a GIT_SSH_KEY secret and adding a step to configure the ssh-agent.

  • Multiple Projects/Workspaces: For monorepos with multiple Terraform projects, you can use an infracost.yml configuration file to define each project and its parameters. The action will automatically detect and use this file.

  • Terragrunt: The Infracost CLI automatically detects Terragrunt projects, so the same workflow can often be used with minor path adjustments.

Conclusion

Integrating Infracost into your GitHub Actions pipeline is a high-impact, low-effort way to implement proactive FinOps. By automating cost estimation and presenting the data directly within pull requests, you embed financial awareness into the core of your engineering workflow. This simple setup provides a powerful safety net that helps prevent budget overruns, facilitates informed discussions about cost, and fosters a culture of cost accountability across your team.

See, Understand, Optimize -
All in One Place

Atler Pilot decodes your cloud spend story by bringing monitoring, automation, and intelligent insights together for faster and better cloud operations.