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.
Getting Started
First we need to install Jest and some other required tools:
1 | npm init -y |
Next we need to setup a config file for Jest. So add the following to the jest.config.ts
file.
1 | export default { |
We’ll be using another library from CDKTF called @cdktf/hcl2json to convert our HCL Terraform files to JSON for testing. So in the __tests__/index.test.ts
file we’ll add the following:
1 | import * as hcl from "@cdktf/hcl2json"; |
And we can generate our first snapshot:
1 | npx jest --updateSnapshot |
This will generate a new directory and file under __tests__
. The new index.test.ts.snap
file will contain the JSON representation of your Terraform files all together.
1 | __tests__ |
Now I can move resources around. In my example this is my original main.tf
file:
1 | resource "null_resource" "resource1" {} |
Now I’ll move my S3 resources to a separate file called s3.tf
:
1 | resource "null_resource" "resource1" {} |
1 | resource "aws_s3_bucket" "test_bucket" {} |
And I can run a test to ensure Terraform still works as expected:
1 | npm test |
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.