Terraforming in 2021 – new features, testing and compliance
Tags: terraform, devops, terratest, inspec
Published: 2021-05-02 17:07:29

---
title: Terraforming in 2021 – new features, testing and compliance
published: true
description: new features in terraform and tools to improve developing code in terraform by introducing better testing mechanisms
tags: terraform, devops, terratest, inspec
//cover_image: https://direct_url_to_image.jpg
---

<p> Both <a href="https://www.linkedin.com/in/jrcferrao/"  target="_blank" rel="noopener noreferrer">João</a> and <a href="https://www.linkedin.com/in/diogoaurelio/"  target="_blank" rel="noopener noreferrer">I</a> have been using regularly terraform for some time now, and are big fans of it. Big enough to even have worked for quite a while on a <a href="https://www.mkops.io/" target="_blank" rel="noopener noreferrer"> side project of our own to simplify managing terraform environments</a> (which unfortunately did not succeed), at least. And yes, now that we are preparing the next one with <a href="https://www.mkops.io/" target="_blank" rel="noopener noreferrer">mklabs</a>, which naturally also heavily relies on terraform scripts, it made only sense to start by sharing some of our favorite tools that gravitate in the terraform ecosystem. 
<p>We kick off with the latest updates in terraform itself, from 0.12 until the latest 0.15, and then go straight to surrounding tooling, where we mainly focus on testing and compliance checking for infrastructure. </p>
<p>You can find all the code supporting this this post <a href="https://github.com/mklabs-io/tf-ecosystem-blog-post" target="_blank" rel="noreferrer noopener" data-type="URL" data-id="https://github.com/mklabs-io/tf-ecosystem-blog-post">here</a>.</p>
<p> </p>
<h3>Overview of latest Terraform versions</h3>
<p>Version 0.15 <a href="https://www.hashicorp.com/blog/announcing-hashicorp-terraform-0-15-general-availability" target="_blank" rel="noopener">has just recently been released</a>. Yet, a lot of companies out there are still running environments up to 0.11.X, and for a good reason. Though version 0.12 was launched already a while ago (2019), it brought great disruption. If this is your case, chances are that you gave up on keep up to date with its progress. Thus, we thought it would make sense to first review some of terraform features you might be missing out, before we try to convince you also considering further improvements.</p>
<h4>0.12</h4>
<ul>
<li><strong>First-class expression syntax</strong>: probably the most noticeable change, no more string interpolation sintax (<em>confettis</em> blowing in the background)!</li>
<li><strong>Generalized type system</strong>: (yay!) able to specify types of variables;</li>
<li><strong>Iteration constructs</strong>: introduction a the <code>for</code> operator allowing closer proximity to programming languages and thus more expressiveness to the DSL;</li>
</ul>
<p>More details, see the <a href="https://www.hashicorp.com/blog/announcing-terraform-0-12" target="_blank" rel="noopener">general availability announcement page</a>.</p>
<h4>0.13</h4>
<ul>
<li><strong>Module improvements</strong> - brings ability to use several meta tags that until so far were only available for <code>resources</code> <a href="https://www.hashicorp.com/blog/terraform-0-13-brings-powerful-meta-arguments-to-modular-workflows" target="_blank" rel="noopener">in modules</a>. In this case, we can now use <code>depends_on</code> for coupling dependencies with modules (finally!), along with ability instantiate multiple module instances with <code>count</code> or <code>for_each</code>; <a href="https://www.hashicorp.com/blog/terraform-0-13-brings-powerful-meta-arguments-to-modular-workflows" target="_blank" rel="noopener">more details here</a>;</li>
</ul>
<p style="text-align: center;"><a href="https://datacenternotes.files.wordpress.com/2021/03/terraform_module_dependency.jpg"><img class="wp-image-4344 aligncenter" src="https://datacenternotes.files.wordpress.com/2021/03/terraform_module_dependency.jpg" alt="" width="599" height="284" /></a>Example specifying a module dependency (a personal favorite), <a href="https://www.hashicorp.com/blog/terraform-0-13-brings-powerful-meta-arguments-to-modular-workflows" target="_blank" rel="noopener">source hashicorp blog</a></p>
<ul>
<li><strong>Custom variable validation</strong> - when specifying variables one can from this version on wards specify custom rules for the input that is accepted and respective error message to allow fast failure; more details here;  </li>
</ul>
<p style="text-align: center;"><a href="https://datacenternotes.files.wordpress.com/2021/03/terraform_variable_validation.jpg"><img class="wp-image-4342 aligncenter" src="https://datacenternotes.files.wordpress.com/2021/03/terraform_variable_validation.jpg" alt="" width="613" height="249" /></a>Example variable validation, <a href="https://www.hashicorp.com/blog/custom-variable-validation-in-terraform-0-13" target="_blank" rel="noopener">source hashicorp blog</a></p>
<ul>
<li><strong>Support 3rd party providers</strong> - terraform now allows one to reference your own <a href="https://registry.terraform.io/browse/providers" target="_blank" rel="noopener">provider</a> in the terraform block <code>required_providers</code>. The <code>required_providers</code> keyword in the terraform block already existed in terraform 12, though with was restricted to hashicorp's own providers; now you can reference your own DNS source to host your own registry, and upon <code>terraform init</code> it will be installed same as it used to all other providers; <a href="https://www.hashicorp.com/blog/automatic-installation-of-third-party-providers-with-terraform-0-13" target="_blank" rel="noopener">more details here</a>; note that if you are already using the <code>required_providers</code> keyword in terraform block, to migrate from version 12 to 13 you should adapt it, as shown in the following example:</li>
</ul>
<p style="text-align: center;"><a href="https://datacenternotes.files.wordpress.com/2021/03/terraform13_providers.jpg"><img class="wp-image-4346 aligncenter" src="https://datacenternotes.files.wordpress.com/2021/03/terraform13_providers.jpg" alt="" width="602" height="334" /></a>Example required_providers, source <a href="https://www.terraform.io/upgrade-guides/0-13.html" target="_blank" rel="noopener">terraform upgrade guides</a></p>
<p>More details, see the <a href="https://www.hashicorp.com/blog/announcing-hashicorp-terraform-0-13" target="_blank" rel="noopener">general availability announcement page</a>.</p>
<h4>0.14</h4>
<ul>
<li><strong>Sensitive variables &amp; outputs</strong> - allowing one to flag a variable as "sensitive" will redact its output on the CLI;</li>
<li><strong>Improved diff</strong> - this is probably one of the most common complaints I hear, namely the difficulty in reading a terraform <code>plan</code> (and along with it the same for <code>apply</code> and <code>show</code>) output; with this new change, it hides unchanged fields (irrelevant for the diff) while displaying a count of the hidden elements for better clarity; <a href="https://www.hashicorp.com/blog/terraform-0-14-adds-a-new-concise-diff-format-to-terraform-plans" target="_blank" rel="noopener">more details here</a>;</li>
</ul>
<p style="text-align: center;"><a href="https://datacenternotes.files.wordpress.com/2021/03/terraform14_improved_diff.jpg"><img class="wp-image-4355 aligncenter" src="https://datacenternotes.files.wordpress.com/2021/03/terraform14_improved_diff.jpg" alt="" width="403" height="471" /></a>Example excerpt diff, <a href="https://www.hashicorp.com/blog/announcing-hashicorp-terraform-0-14-general-availability" target="_blank" rel="noopener">source hashicorp blog</a></p>
<ul>
<li><strong>dependency lockfile</strong> - as soon as you run <code>terraform init</code> with version 14 you will notice that a <code>.terraform.lock.hcl</code> file will be created in that directory and outside the <code>.terraform</code> directory. This file is intended to be added to version control (git committed), to guarantee that the exact same provider versions are run everywhere;</li>
</ul>
<p>More details, see the <a href="https://www.hashicorp.com/blog/announcing-hashicorp-terraform-0-14-general-availability" target="_blank" rel="noopener">general availability announcement page</a>.</p>
<p> </p>
<h4>0.15</h4>
<p>Finally, here are some of the main highlights the latest version just very recently announced:</p>
<ul>
<li><strong>Remote state data source compatibility</strong>: in order to make it easier to upgrade to newer versions, you can use reference remote state data objects that are using older versions; note that this feature has been back ported into previous releases as well, namely 0.14.0, 0.13.6, and 0.12.30;</li>
<li><strong>Improvements to conceal sensitive values (passwords, for example)</strong>: following version 0.14 work now provider developers can specify the properties that are by default sensitive and should be anyway hidden in outputs; moreover, terraform also added a function (sensitive) for users to be able to explicitly hide values;</li>
<li><strong>Improvements in logging behavior</strong>: ability to control provider and terraform log level separately <code>TF_LOG_CORE=level</code> and <code>TF_LOG_PROVIDER=level</code>.</li>
</ul>
<p>More details, see the <a href="https://www.hashicorp.com/blog/announcing-hashicorp-terraform-0-15-general-availability" target="_blank" rel="noopener">general availability announcement page</a>.</p>
<p> </p>
<h3>Handling multiple versions</h3>
<p>Assuming that these new features convinced you to upgrade your existing terraform environments, being realistic here, this will not happen from one day to another. You will have a transition period (if not permanently) where you have environments with different terraform versions. That is OK, you can still keep your sanity while hopping between all of them thanks to tools like the following:</p>
<ul>
<li><a href="https://github.com/tfutils/tfenv">TFEnv</a> - terraform environment switcher inspired (from the ruby world) by <code>rbenv</code> written with shell scripts;</li>
<li><a href="https://github.com/warrensbox/terraform-switcher/">Terraform Switcher </a>- yet another project essentially doing the same written in go;</li>
</ul>
<p>Both of these projects overlap almost entirely, so we will simply exemplify with one of them, namely tfenv:</p>

<!-- wp:image {"align":"center","id":4330,"width":529,"height":322,"sizeSlug":"large","linkDestination":"media"} -->
<div class="wp-block-image"><figure class="aligncenter size-large is-resized"><a href="https://datacenternotes.files.wordpress.com/2021/03/tfenv_demo.gif"><img src="https://datacenternotes.files.wordpress.com/2021/03/tfenv_demo.gif?w=1024" alt="" class="wp-image-4330" width="529" height="322"/></a></figure></div>
<!-- /wp:image -->

<!-- wp:paragraph -->
<p></p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Here we are showing how you can switch between installed versions <code>tfenv use &lt;local-version&gt;</code>, how you can check which versions are already locally installed with <code>tfenv list</code>, all versions currently available <code>tfenv list-remote</code> (minor detail: the current version of the library I'm using to record my terminal, <a href="https://terminalizer.com/docs">terminalizer</a>, does not capture me scrolling up and selecting version terraform <code>0.14.5</code>)<br>Last but not least, we also show a cool feature from tfenv, namely the ability to automatically recognize the minimum required version in a given environment. Same goes for the latest version, in case you are wondering. And yes, this is also available in terraform switcher project.</p>
<!-- /wp:paragraph -->

<!-- wp:heading {"level":3} -->
<h3>Testing</h3>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>Testing is probably the most confusing topic in the Infrastructure-as-Code (IaC) land, and terraform not being an exception, as a lot of different tools and procedures get thrown in this same bag, when, well, they probably should not. Usually when talking about testing, people usually mean three different things:</p>
<!-- /wp:paragraph -->

<!-- wp:list -->
<ul><li><strong>static checks</strong> - validation of mainly the structure code without actually running the code; a fast away for performing sanity checks, either local and/or in your CI/CD pipelines; </li><li><strong>integration tests</strong> - provided you are properly using inversion of control with variables, they give you the power to test your modules or environments for different generic cases;</li><li><strong>compliance checks</strong> - tests done in the aftermath, after all resources have already been deployed; these can serve distinct purposes that we will explore better later, but essentially the goal is to confirm that what is deployed is what was initially intended and expressed in terraform;</li></ul>
<!-- /wp:list -->

<!-- wp:paragraph -->
<p>Yes, you got that right: if you were looking forward to some classic unit testing, you can forget that for now. Let us dive straight into more details.</p>
<!-- /wp:paragraph -->

<!-- wp:heading {"level":4} -->
<h4>Static checks</h4>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>Again, these are not tests strictly speaking, but rather just simple validation checks one can run to catch common errors without actually deploying anything. There is an array of tools out there, but let us start with the one provided out of the box in terraform binary.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>It is not uncommon for the tool creators to provide their own validators. Kubernetes provides validate <code>kubectl apply -f &lt;file&gt; --dry-run --validate=true</code>, helm provides lint <code>helm lint &lt;path&gt;</code>; terraform provides <code>validate</code>. </p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>In the following example running <code>terraform validate</code> would catch two of the three issues:</p>
<!-- /wp:paragraph -->

{% gist https://gist.github.com/diogoaurelio/81fb0b1f4bcb927dd3f9e046ce9a9427 %}
<figure class="wp-block-embed is-type-rich is-provider-embed wp-block-embed-embed"><div class="wp-block-embed__wrapper">

</div></figure>
<!-- /wp:embed -->

<!-- wp:paragraph -->
<p>Validate will require to have previously run <code>terraform init</code>, so that it can leverage providers. In our example it will detect the typo in the aws bucket resource reference, along with the invalid CIDR provided to create the VPC. What it will not detect, however, is the non existent EC2 instance type.</p>
<!-- /wp:paragraph -->

<!-- wp:image {"align":"center","id":4373,"width":595,"height":346,"sizeSlug":"large","linkDestination":"media"} -->
<div class="wp-block-image"><figure class="aligncenter size-large is-resized"><a href="https://datacenternotes.files.wordpress.com/2021/03/terraform_validate_demo.gif"><img src="https://datacenternotes.files.wordpress.com/2021/03/terraform_validate_demo.gif?w=1024" alt="" class="wp-image-4373" width="595" height="346"/></a></figure></div>
<!-- /wp:image -->

<!-- wp:paragraph -->
<p><a rel="noreferrer noopener" href="https://github.com/terraform-linters/tflint" target="_blank">TFLint</a> comes to the rescue. Being yet another open source tool written in go, it comes as a binary much like terraform and does not even require terraform to be installed. </p>
<!-- /wp:paragraph -->

<!-- wp:image {"align":"center","id":4376,"width":600,"height":348,"sizeSlug":"large","linkDestination":"media"} -->
<div class="wp-block-image"><figure class="aligncenter size-large is-resized"><a href="https://datacenternotes.files.wordpress.com/2021/03/tflint.gif"><img src="https://datacenternotes.files.wordpress.com/2021/03/tflint.gif?w=1024" alt="" class="wp-image-4376" width="600" height="348"/></a></figure></div>
<!-- /wp:image -->

<!-- wp:paragraph -->
<p>Running with the <code>deep</code> option requires one to provide credentials, providing a more thorough inspection. In our case, it detected the incorrect instance type, as well as the wrong AMI.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>You can also <a rel="noreferrer noopener" href="https://github.com/terraform-linters/tflint/blob/master/docs/user-guide/config.md" target="_blank">customize tflint</a> to inject variables, define modules to ignore, etc. You can check the <a href="https://github.com/terraform-linters/tflint/tree/master/docs/user-guide" target="_blank" rel="noreferrer noopener">user guide</a> for more details.  </p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Now besides linting for configuration issues in your code, another recommendation is to <em>check for security issues</em>, such as too permissive security group rules, unencrypted resources, etc. </p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Here again more than one tool exists to assist. We will highlight two of the most popular ones here: <a rel="noreferrer noopener" href="https://github.com/tfsec/tfsec" target="_blank">tfsec</a> and <a rel="noreferrer noopener" href="https://github.com/bridgecrewio/checkov" target="_blank">checkov</a>. Both provide a predefined set of checks that they use to inspect your code, allowing to explicitly open exceptions (if you really want to) by annotating your code with comments, and adjust the configuration to ignore some modules, for example. </p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>TFSec is written in Go, and is probably the fastest to get started, and currently <a rel="noreferrer noopener" href="https://tfsec.dev/docs/aws/home/" target="_blank">provides up to 10 checks</a> for the current main cloud providers (AWS, GCP, and Azure). The potential downside is that works exclusively for Terraform, so you will need to use additional tools to inspect kubernetes/helm/cloudformation etc. </p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Checkov, on the other hand, despite being a more recent tool, has seen stellar development speed (being developed by a <a rel="noreferrer noopener" href="https://bridgecrew.io/round-a-announcement/" target="_blank">startup with good founding rounds</a>, and <a rel="noreferrer noopener" href="https://www.paloaltonetworks.com/company/press/2021/palo-alto-networks-announces-intent-to-acquire-bridgecrew" target="_blank">PaloAlto Networks acquisition</a> can't hurt). Not only do they have a <a href="https://docs.bridgecrew.io/docs/aws-policy-index">really comprehensive number of checks</a> across all the main cloud providers, but they also span across multiple technologies, such as Kubernetes, Cloudformation, serverless and ARM templates. And the list keeps growing. Checkov provides you the option to run either a pure static check by just pointing to the terraform directory or terraform file, or by actually running it against a terraform plan file. The nice thing about running it directly is naturally the simplicity of not requiring to have the target environment accessible to test the code.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p></p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>These tools are grabbing a lot of attention lately, as the double checking for security issues was usually locked in the hands of devops/devsecops teams, which in practice constituted a development bottleneck. By injecting these checks early in CI/CD pipelines, a great deal of development speed is freed without compromising security.   </p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p></p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p><strong>Integration tests</strong></p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p><a rel="noreferrer noopener" href="https://github.com/gruntwork-io/terratest" target="_blank">Terratest</a> is probably the closest one can get now a days to testing the specific peace of terraform code. It is a Go library, and requires one to write tests in Go. This is obviously a potential limitation as not all teams have knowledge in Go. On the upside, I would argue that the learning curve of learning Go to get the basics - read enough for writing terraform tests - is not steep if you know already at least one programming language. </p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Having worked already in several Go projects in the context of mklabs, we're naturally favorably biased towards Terratest. So, even if you have never tried Go, we would still recommend having a look on our sample repository, where we provide go mod setup to make it easy getting started. And if this did not convince you yet, here's what might: you can also use Terratest to test Dockerfiles, Kubernetes and Packer setups. </p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>This might seem intimidating, but we would argue that the benefits are worth it. Let us look at an example skeleton of a test setup for AWS:</p>
<!-- /wp:paragraph -->

{% gist https://gist.github.com/diogoaurelio/53cb1f70173399341cc95df52015e6d8 %}
 

<!-- /wp:embed -->

<!-- wp:paragraph -->
<p>Essentially the skeleton is always the same: </p>
<!-- /wp:paragraph -->

<!-- wp:list {"ordered":true} -->
<ol><li>start by defining the variables you want to inject as input for your terratest run; you might want to rather inject random variables even, to test in greater depth;</li><li>make sure you tell the setup to destroy all created resources after the terraform apply has been completed using the <code>defer</code> statement; this is equivalent to the <code>trap</code> keywork in shell, and it will execute even if something fails in the meanwhile; the only prerequisite is that you declare it before you call <code>terraform.InitAndApply()</code> method;</li><li>Let the test be deployed by passing the terraform config setup you have previously declared in <code>terraformOptions</code> to <code>terraform.InitAndApply</code> method;</li><li>Finally, declare the things you want to assert; that is, declare what you expect should have been deployed - the <code>expected</code> - and see if they match what was actually deployed - the <code>result</code>. The simplest way is to check in terraform apply output, which is accessible via `terraform.Output()` method. Alternatively, terragrunt also provides you some methods out of the box for frequently checked things on a per provide basis.  </li></ol>
<!-- /wp:list -->

<!-- wp:paragraph -->
<p>Sounds like fun, right? Here is an example of some of the tests we could write to our basic terraform example:</p>
<!-- /wp:paragraph -->

{% gist https://gist.github.com/diogoaurelio/99cf2d6dbe53e7df502717b341b873a3 %}

<!-- wp:paragraph -->
<p>Here is the output of running these tests for our demo setup:</p>
<!-- /wp:paragraph -->

<!-- wp:image {"id":4397,"sizeSlug":"large","linkDestination":"media"} -->
<figure class="wp-block-image size-large"><a href="https://datacenternotes.files.wordpress.com/2021/03/terratest_demo-1.gif"><img src="https://datacenternotes.files.wordpress.com/2021/03/terratest_demo-1.gif?w=1024" alt="" class="wp-image-4397"/></a></figure>
<!-- /wp:image -->

<!-- wp:paragraph -->
<p><strong>Final thoughts regarding terratest</strong>: we find terratest a great tool to implement changes in your infrastructure with confidence, no matter if they are just simple day to day changes, or bigger and complexer upgrades or migrations. </p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>We just scratched the surface here on the tests one can develop with terratest - for example combining SSH access into instances and confirming access to resources, etc. However, there are no free lunches, and this can come at a price: tests can take a long time (depending obviously on what you are testing), and require a non trivial time investment - learning how to use, writing them, and setting up the environment, as you probably will want to run them in an isolated environment. For example, in AWS case, this would ideally be a dedicated account. We recommend reading <a href="https://terratest.gruntwork.io/docs/#testing-best-practices">best practices on how to perform testing</a> from terragrunt, the company behind terratest.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p> </p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p><strong>Compliance checks</strong></p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>The last mile is asserting that what you wanted to be deployed, was indeed deployed exactly <em>as you wanted</em>. Abusing terraform <code>null_resource</code> is a classic one leading to unintended surprises. One way of achieving this would be to run these tests right after the <code>terraform apply</code> stage of your CI/CD pipeline.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>But the next question you might have is how do I know that these configurations stay that way, that <em>no one changed things inadvertently</em> ? We've seen this situation arise in different forms: changes done by users manually via GUI or CLI; via different terraform environments mutating overlapping resources properties; or as a by-product of using different IaC tools, for example configuring some bits with Cloudformation, some K8s or Helm, etc. </p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Arguably more interesting would be scheduling to run these checks continuously and repeatedly, to make sure things stay as you expected. Let's see some options out there to achieve this.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p></p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p><strong>The rogue approach</strong>: in practice you can do this type of compliance checks with any programming language you favor.  As we shown before, one can export terraform' state into <code>json</code> format, and then use, for example, python with <code>pytest</code> and <code>boto3</code> libraries to compare what is deployed with the desired output. You could even go further, and use <code>boto3</code> to scan your accounts for different aspects that you considered go against best practices, such as lack of encryption (in-flight and at rest).</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>While this might be tempting at first sight, you might end up writing way more testing code, than the actual terraform code. Not only it seems kind of silly, but it can get hairy.    </p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>The second reason not to follow this approach, is that there are already several solutions out there fairly tested and intuitive to use that can help you with this task, which we will cover now:</p>
<!-- /wp:paragraph -->

<!-- wp:list -->
<ul><li>Driftctl - open source go library from cloudskiff for terraform;</li><li>Sentinel - Hashicorp's own solution;</li><li>terraform-compliance - open source BDD based solution dedicated for terraform;</li><li>Conftest - test suite for multiple frameworks besides terraform, such as kubernetes and dockerfiles; </li><li>Inspec - Chef compliance testing tool, written in ruby;</li><li>Built-in cloud provider - each cloud provider has it's own inspections mechanisms in place;</li></ul>
<!-- /wp:list -->

<!-- wp:paragraph -->
<p>You may be wondering why the first place in our list is a library still in beta. That is a good point, and we would argue that its progress seems to be promising, and that we like to support startups. Moreover we think its <a rel="noreferrer noopener" href="https://docs.driftctl.com/0.7.1/usage" target="_blank">simplicity of usage</a> deserves a highlight as it delivers one thing and one thing only: check if what is in your terraform state file is what is actually deployed. Simply point to your terraform statefile when you run <code>driftctl scan</code> command and you will get a detailed report if you have <em>drifted</em>. Due to the low effort required to implement this library and value provided, we think it deserves taking it for a spin.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Next on our list is Hashicorp's (the company behind terraform) own enterprise solution for this, <a rel="noreferrer noopener" href="https://www.hashicorp.com/sentinel" target="_blank">Sentinel</a>. This is could make sense if you are already using other Hashicorp's enterprise functionality, benefiting from Terraform Enterprise.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>A direct open source comparable alternative would be using <a rel="noreferrer noopener" href="https://github.com/terraform-compliance/cli" target="_blank">terraform-compliance</a>. It follows <a rel="noreferrer noopener" href="https://en.wikipedia.org/wiki/Behavior-driven_development" target="_blank">BDD</a> directives so that you can specify in an easy human readable way your expectations, using:</p>
<!-- /wp:paragraph -->

<!-- wp:list -->
<ul><li><em>given</em>: a given resource type;</li><li><em>when</em>: an optional condition you might want to add;</li><li><em>then</em>: what you expectation is;   </li></ul>
<!-- /wp:list -->

<!-- wp:paragraph -->
<p>Here is an example of a test file for AWS S3 buckets:</p>
<!-- /wp:paragraph -->

{% gist https://gist.github.com/diogoaurelio/7051a158e366edaeca1b937290757102  %}

<!-- wp:paragraph -->
<p>Although we do get the appeal of easily understandable tests that do not require knowing how code, we find terraform-compliance lacks flexibility to test various aspects, mainly due to the BDD nature. Moreover, there are <a rel="noreferrer noopener" href="https://adinermie.com/the-good-the-bad-and-the-ugly-of-using-terraform-compliance/" target="_blank">more people disenchanted by it with some valid points</a>. </p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>If you like terraform-compliance, <a rel="noreferrer noopener" href="https://github.com/open-policy-agent/conftest" target="_blank">Conftest</a> might also be worth having a look. It has its own DSL to write policies, and allows you to test multiple frameworks. We found <a rel="noreferrer noopener" href="https://www.blokje5.dev/posts/validating-terraform-plans/" target="_blank">this blog post</a> from Lennard Eijsackers very informative, and would thus rather recommend you to check it out. </p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p></p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Before we dive into own cloud provider compliance checking services, we want to highlight yet another open source tool, namely <a rel="noreferrer noopener" href="https://github.com/inspec/inspec" target="_blank">InSpec</a>. It allows you to write tests in ruby, and was <a rel="noreferrer noopener" href="https://docs.chef.io/inspec/inspec_and_friends/#rspec" target="_blank">built on top of RSpec</a>. If you know already <a rel="noreferrer noopener" href="https://github.com/k1LoW/awspec" target="_blank">awsspec</a>, then this should feel very similar, with the advantage that InSpec also supports GCP and Azure. </p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Even though none of us is actively a ruby developer, we find InSpec very easy to get started with and, most importantly, very powerful. It allows you to combine IaC checks to target resources deployed and mapped in terraform state files, with other general policies for cloud account configuration. Moreover, it also allows you to combine additional security checks, such as on OS level configurations and services running. Let us illustrate how you could write these checks. The following check illustrates how to define global policies that an account should obey:</p>
<!-- /wp:paragraph -->

{% gist https://gist.github.com/diogoaurelio/40ad95bfae60702b2970e2ac435598d6 %}

<!-- wp:paragraph -->
<p>The next one illustrates for generic networking:</p>
<!-- /wp:paragraph -->

{% gist https://gist.github.com/diogoaurelio/833d87f6acbc2d53b68b3ae4a5c5e3aa %}

<!-- /wp:embed -->

<!-- wp:paragraph -->
<p>The previous examples only illustrate generic control checks that validate overall best practices in your acocunt. However, you might want to also perform assertions regarding what is in your terraform state versus what is deployed - what the <a rel="noreferrer noopener" href="https://cloudskiff.com/" target="_blank">cloudskiff</a> engineers rightly name <em>drift</em>. Christoph Hartmann - one of InSpecs creators -  has a nice <a rel="noreferrer noopener" href="https://lollyrock.com/posts/inspec-terraform/" target="_blank">blog post</a> explaining how to use InSpec and integrate with terraform. The approach is essentially as described previously in the rogue approach - import terraform state json file and use it as the expected assertion. </p>
<!-- /wp:paragraph -->

<!-- wp:heading {"level":3} -->
<h3>Built-in cloud provider policy tools</h3>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>Each cloud provider has a native tool to address company-wide governance policies. Some examples of services are: </p>
<!-- /wp:paragraph -->

<!-- wp:list -->
<ul><li>AWS: <strong><a href="https://aws.amazon.com/config/">AWS Config</a></strong> and to manage cloud configuration deviations within one account, <a rel="noreferrer noopener" href="https://aws.amazon.com/systems-manager/" target="_blank">Systems Manager</a> to enforce instance OS security, and more recently <a rel="noreferrer noopener" href="https://aws.amazon.com/controltower/" target="_blank">Control Tower</a> for enforcing rules across multiple accounts;</li><li>Azure: <strong><a href="https://azure.microsoft.com/en-us/services/azure-policy/">Azure Policy</a></strong> for checking cloud configuration deviations and <strong><a href="https://azure.microsoft.com/en-us/services/security-center/">Azure Security Center</a></strong></li><li>GCP:<strong> <a href="https://cloud.google.com/blog/products/identity-security/protecting-your-gcp-infrastructure-at-scale-with-forseti-config-validator">Forseti Config Validator</a></strong> for GCP</li></ul>
<!-- /wp:list -->

<!-- wp:paragraph -->
<p>These are just some of the services that we know that can be used for such enforcement. Most of these services go beyond just checking cloud config, and also provide security inspections at instance level, for example. The important point to keep in mind is that these security checks are post deployment compliance assertion, not for preventing configuration issues.</p>
<!-- /wp:paragraph -->

<!-- wp:heading -->
<h2>Final thoughts</h2>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>We find that there is not a single silver bullet that solves all problems, and the best strategy is actually a combination of multiple tactics employed at different stages. The two main phases that require different approaches are <em>pre</em> and <em>post</em> deployment. </p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>For pre-deployment, a combination of static checks and actual tests can be used. Static checks are a great starter, as they are easy to setup, and allow you to enforce generally good practices across the whole organization. In other words, static checks provide you an powerful easy win. With terratest, on the other hand, you mainly gain on confidence that the IaC code will actually work, and that you will catch <em>faux pas</em>. However, terratest does not come for free, and does require a learning curve with go, along with time investment to develop the actual tests.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>After your code gets deployed comes the next challenge: making sure things stay well architected. Regular scheduled checks that assess if your infrastructure is running as intended should also be part of your devOps strategy, and for this two main routes exist: open source or using dedicated cloud services.   </p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>And that is it. Thank you for reading, we hope this has been useful. Feel free to reach out to us if you have questions or suggestions.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Once again, you can find all the code supporting this this post <a rel="noreferrer noopener" href="https://github.com/mklabs-io/tf-ecosystem-blog-post" data-type="URL" data-id="https://github.com/mklabs-io/tf-ecosystem-blog-post" target="_blank">here</a>. </p>
<!-- /wp:paragraph -->

<!-- wp:heading {"level":3} -->
<h3>Sources</h3>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>As usual, here is the summary of sources used for this post:</p>
<!-- /wp:paragraph -->

<!-- wp:list -->
<ul><li><a rel="noopener" href="https://www.hashicorp.com/blog/announcing-terraform-0-12" target="_blank">Terraform version 12 general availability notes</a></li><li><a rel="noopener" href="https://www.hashicorp.com/blog/announcing-hashicorp-terraform-0-13" target="_blank">Terraform version 13 general availability notes</a></li><li><a rel="noopener" href="https://www.hashicorp.com/blog/announcing-hashicorp-terraform-0-14-general-availability" target="_blank">Terraform version 14 general availability notes</a></li><li><a href="https://github.com/warrensbox/terraform-switcher/">Terraform Switcher project</a></li><li><a href="https://terratest.gruntwork.io/docs/#testing-best-practices">Best practices testing with terratest</a></li><li><a rel="noreferrer noopener" href="https://github.com/tfsec/tfsec" target="_blank">TFSec</a></li><li><a rel="noreferrer noopener" href="https://github.com/bridgecrewio/checkov" target="_blank">Bridgecrew checkov</a></li><li><a rel="noreferrer noopener" href="https://github.com/terraform-compliance/cli" target="_blank">Terraform compliance</a></li><li><a rel="noreferrer noopener" href="https://github.com/cloudskiff/driftctl" target="_blank">Driftctl tool</a></li><li><a rel="noreferrer noopener" href="https://docs.chef.io/inspec/" target="_blank">Chef InSpec</a></li><li><a href="https://lollyrock.com/posts/inspec-terraform/" target="_blank" rel="noreferrer noopener">Christoph Hartmann blog post how to use Inspec with terraform</a> </li><li><a href="https://github.com/k1LoW/awspec">AWS Spec</a></li><li><a rel="noreferrer noopener" href="https://github.com/open-policy-agent/conftest" target="_blank">Conftest</a></li><li><a rel="noreferrer noopener" href="https://www.blokje5.dev/posts/validating-terraform-plans/" target="_blank">Blog post from Lennard Eijsackers on Conftest</a></li><li>The recordings of my terminal were done using <a href="https://terminalizer.com/">terminalizer</a></li></ul>
<!-- /wp:list -->

<!-- wp:paragraph -->
<p></p>
<!-- /wp:paragraph -->