Usually when creating a Terraform module you start with the defacto standard of a main.tf file. As things grow maybe you will add in a variables.tf or outputs.tf file. Terraform treats these all as if they were a single file. As things grow it can be helpful to start structuring things in related files.
Maybe I have an S3 bucket with some related resources that I want to move from main.tf to s3.tf. How can I validate that I haven’t copy/pasted in error? Sure I can deploy and test it, but my changes are really minor. Is there an easy way to validate this type of change? Yes, there is.
Jest + Terraform
Utilizing Jest we can take a snapshot of the current state of our Terraform files, concat them together into a single JSON file and compare them with previous values to make sure it works.
First we need to install Jest and some other required tools:
And I can run a test to ensure Terraform still works as expected:
1 2 3 4 5 6 7 8 9 10 11 12 13 14
> email@example.com test > jest
PASS __tests__/index.test.ts Terraform Snapshot ✓ Should have resources with required properties (89 ms)
Test Suites: 1 passed, 1 total Tests: 1 passed, 1 total Snapshots: 1 passed, 1 total Time: 0.572 s, estimated 1 s Ran all test suites.
Now I can move around resources, data lookups outputs and variables to my hearts content and still validate the results are the same. If I ever need to update snapshots I can re-run the npx jest --updateSnapshot command, compare the new vs old snapshot it git and consider it good.