Infrastructure testing for Terraform with Clarity

DevOps Engineering is a reality. DevOps principles like Immutable Infrastructure, Infrastructure as Code, GitOps and Observability are the default building principles for any cloud computing serious initiative. However, Infrastructure, provisioning, automation it's not trivial, tools like Ansible and Terraform make the engineer's life easier, productivity and fun. As time goes by we have more and more infrastructure code, how we make sure we keep software rolling faster with stability and quality?  The answer is testing.  Infrastructure testing is a very tricky, mocking terraform it's not easy. There are some interesting solutions like LocalStackTestContainers, and molecule for Ansible. These tools are great but they are more towards Integration or E2E testing with are expensive, involve several other components and often super slow to run. A simple approach more towards unit testing could be achieved using Clarity.

Enter Clarity

Clarity is a BDD(Behavior Driven Development) framework for Terraform. Clarity is a simple, single binary written in Go. Clarity uses *gherkin* as syntax. Clarity has its own set of matchers and HCL
parser. Clarity has an extensive set of matchers like:

  • always equal
  • never equals
  • does not equal
  • is greater than
  • is less than
  • exists
  • occurs (at least, at most, exactly) x times

All the matchers can be used for Terraform attributes or even for terraform values. Clarity is great but you need to keep in mind that clarity will check for static values, it would get dynamic values, so it's a great tool to hook on your PR add-ons or even as part of your CI/CD/GitOps pipeline.

Sample Code & Usage

After downloading the binary, adding to the path and getting proper execution permissions you need to have the binary on the same folder as terraform files are located. So you do your terraform files(*.tf) as usual and them you create *.feature file where we will have our specs for testing. Then after having all that we can run the tests via console, i.g: clarity main.feature. Let's take a look at the following sample.

As you can see the syntax is pretty simple and straight forward you provide the attributes and the values you expect to have in your terraform files and clarity will check it for us. There is this interesting extension you can install for VSCode which will make your life easier.

Running clarity will output something as similar:

The complete sample is here in my github.

Diego Pacheco

Popular posts from this blog

Kafka Streams with Java 15

Rust and Java Interoperability

HMAC in Java