Terraform (IaC – Infrastructure as Code) Testing

By | June 20, 2021

Terraform is an Infrastructure as Code tool that enables us to deploy predictable infrastructure.

Usually for the Software/Data applications we focus on writing code, testing it, making sure its following all the conventions, making sure there are no security issues, etc. etc.

But when it comes to deploying Infrastructure, we don’t normally treat Terraform or any other equivalent in the same way. But why is that?…Isn’t any code prone to bugs, inconsistencies and manual errors? 🤔

Before Cloud, we have been writing YAMLs, bash scripts, perl, etc. We would test it, but not in the same way as Application code. With the Cloud era, this gap is slowly fading away. There are a lot of libraries now available to make Infrastructure much more robust.

Below is one way of enforcing some tests for terraform code:

Terraform Testing
  1. Development
  • When a developer writes code and hits commit, we can use checkov (https://github.com/bridgecrewio/checkov) pre-commit hook to scan the code changes and make sure all tests passes, no misconfiguration, etc.
  • Once all test passes, code is committed. Developer can then push the code to Git (or any other code repository) and raise a Pull Request
  • You have already avoided manual errors going into git commit history just by doing this!

2. CI

  • In the CI tool you are using (Gitlab runner/Jenkins/anything else), you could add multiple steps you want to execute when the PR(Pull Request) gets raised. I am just highlighting few obvious ones
  • tflint – This checks for code formatting and conventions
  • checkov – scan modules, run unit tests
  • terraform compliance (https://terraform-compliance.com/) – Security and Compliance tests

3. Code repository

  • Once all tests passes, code is successfully merged to remote branch of Git repository

4. Deploy

  • Now you can either trigger the deploy/terraform-apply via CI or by manually approval process to deploy the infrastructure changes you want to make

I would also suggest taking advantage of Terraform registry of modules (https://registry.terraform.io/). This is battle tested code and can save you weeks worth of time 🙂

Choose Hashicorp verified modules which are more reliable

Terraform VPC

Leave a Reply

Your email address will not be published. Required fields are marked *