Automate Cost Estimation with Infracost and GitHub Actions Based on Your Terraform Code

Managing cloud infrastructure costs is crucial for any DevOps or cloud engineer. Infracost provides an excellent way to estimate cloud costs directly from your Terraform code. By integrating Infracost with GitHub Actions, you can automate cost estimations, making it easier to manage your cloud expenses efficiently.
In this guide, we will walk through setting up Infracost, configuring a GitHub Actions workflow, and generating cost breakdowns for your infrastructure as code (IaC).
Prerequisites
Before we begin, ensure you have the following:
- A GitHub repository containing your Terraform code.
- A GitHub Actions workflow file.
- An Infracost API key (sign up at Infracost if you don't have one).
Step 1: Setting Up Infracost
First, we need to install Infracost in our GitHub Actions workflow. Here is the sample workflow file:
https://github.com/pradeep-kudukkil/infracost/blob/main/.github/workflows/infracost.yml
Step 2: Configuring the GitHub Actions Workflow
- Checkout Code
The first step is to check out your repository's code:
- name: Checkout code
uses: actions/checkout@v2
- Setup Terraform
Next, set up Terraform using the HashiCorp GitHub Action:
- name: Setup Terraform
uses: hashicorp/setup-terraform@v1
with:
terraform_wrapper: false
- Install Infracost
Install Infracost by running the installation script:
- name: Install Infracost
run: |
curl -sSL https://raw.githubusercontent.com/infracost/infracost/master/scripts/install.sh | sh
- Checking Cost
Finally, configure Infracost with your API key and generate a cost breakdown:
- name: Checking cost
run: |
infracost configure set api_key "${{ secrets.INFRACOST_API_KEY }}"
infracost breakdown --path .
Step 3: Adding Secrets to GitHub
To securely store your Infracost API key, add it as a secret in your GitHub repository settings:
- Go to your repository on GitHub.
- Click on Settings.
- In the left sidebar, click on Secrets and variables > Actions.
- Click New repository secret.
- Add INFRACOST_API_KEY as the name and your API key as the value.
Conclusion
By integrating Infracost with GitHub Actions, you can automate the process of cost estimation for your Terraform code. This setup will help you manage and forecast your cloud infrastructure expenses more effectively.
Feel free to customize the workflow according to your specific requirements and extend it with additional steps as needed.
Stay tuned for more tutorials on managing your infrastructure with the best DevOps practices!