Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to test terraform templates other than trial and error

Tags:

terraform

I'm creating cloud resources using Terraform. Each resource is expected to be in a particular desired state after provisioning. For example, when I create a Google Cloud Bucket, I would like certain permissions to be applied automatically. So, my plan contains necessary code for this but I wanted to make sure that this works all the time regardless before I apply. Is there any testing tool/library that can help here?

like image 340
Sahas Avatar asked Dec 14 '22 23:12

Sahas


1 Answers

Yes, I had the same thinking before. Currently, I use several ways to reduce the risk when I apply a new terraform change.

They can't guarantee a 100% successful terraform apply, but will fix the most issues before you apply it.

  1. Validate terraform configuration files.

Terraform has the validate function for starting. But it is not smart enough to go through subfolders. I create a small shell function and add in CI/CD pipeline to run it automatically before terraform apply.

validate() {
  modules=$(find . -type f -name "*.tf" -exec dirname {} \;|sort -u)
  for m in ${modules}
  do
    (terraform validate "$m" && echo "√ $m") || exit 1
  done
}

Of course, do terraform fmt before you submit your change is not bad idea.

  1. terraform plan

@Martin Atkins explained it already, and terraform.io has details about this command.

  1. run automation test kitchen.

That's a test Kitchen plugin for testing Terraform configurations

https://github.com/newcontext-oss/kitchen-terraform

That's an integration test. The test will run in separate VPC with as more as test cases you added. Add the automation test in CI/CD pipeline as well to trigger an automation test every time when you raise merge request to master branch. Apply the change only after getting the test passed.

like image 96
BMW Avatar answered Mar 16 '23 10:03

BMW