1 of 9

How to test your Terraform code

24.JUN.2022

2 of 9

Senior DevOps Engineer

Rafael Natali

  • 4+ years of experience with DevOps ecosystem (CI/CD, K8s, IaC, Cloud, open source)
  • 15+ years overall IT experience
  • HashiCorp Certified: Terraform Associate
  • Google Professional Cloud DevOps Engineer
  • 6x AWS Certified

rafael.natali@marionete.co.uk

https://github.com/rafaelmnatali

https://marionete.co.uk

2

© 2022 Marionete Limited

3 of 9

Why do you need to test your infrastructure?

Why “Terraform Plan” is not enough?

Introduction to “Terraform Test”

Testing your infrastructure - DEMO

“Terraform Test” limitations

1

2

3

4

5

© 2022 Marionete Limited

4 of 9

Test-driven infrastructure

Why do you need to test your infrastructure?

  • Understand if code is doing what it’s supposed to. 
  • Analyse configurations and dependencies before execution.
  • Check if the infrastructure is configured correctly.
  • Convert infrastructure requirements into test cases (TDD).

4

© 2022 Marionete Limited

5 of 9

Plan output

Why “Terraform Plan” is not enough?

  • It does not verify if you have permission to execute the task.
  • Dynamic content is only known after the apply

TERMINAL

  • # module.gcs_bucket["eu"].google_storage_bucket.bucket will be created

+ resource "google_storage_bucket" "bucket" {

+ force_destroy = true

+ id = (known after apply)

+ location = "EU"

+ name = (known after apply)

...

5

© 2022 Marionete Limited

6 of 9

“Terraform Test”

Introduction to “Terraform Test”

  • Experimental feature that allows us to write Terraform module tests in the Terraform language itself.
  • Available since Terraform CLI v0.15.0
  • It’s a separate command for more conveniently running multiple tests in a single action.
  • Apply and Destroy testing model

6

© 2022 Marionete Limited

7 of 9

DEMO – GCP Buckets

Testing your infrastructure

  • Bucket creation.
  • Bucket creation in multiple locations.

7

© 2022 Marionete Limited

8 of 9

Experimental feature

“Terraform Test” limitations

There are a few limitations on how it works. The two main limitations I’d like to highlight are:

  • Currently tests written in this way can only exercise the create and destroy behaviours.
  • Capturing context about failures. “Terraform test” is limited in how much context it's able to gather about failures.

Please, refer to the Hashicorp documentation for a complete list.

8

© 2022 Marionete Limited

9 of 9