learn-terraform

Course outlines for learning terraform.

View the Project on GitHub robertdebock/learn-terraform

Testing experiment

expected time requirements
30 minutes A computer with Terraform installed, terraform knowledge.

Goal: Try the new “testing” experiment.

Explanation

Terraform spins up resources, you can test if that works in CI. But, by testing terraform apply, you basically test if Terraform was able to spin up the resources, not if whatever you spun up actually works.

Functional testing could include some of these cases:

There are probably many more cases you may describe.

Howto

WARNING: Here be dragons, the testing experiment is not very stable or intuitive.

An extra directory must be created: tests. In there a directory default must be created. (See “limitation-1”)

In that directory (tests/default/) you can add any .tf file to describe the tests.

Because this is an experiment, you need to explicitly enable the “provider”.

terraform {
  required_providers {
    test = {
      source = "terraform.io/builtin/test"
    }
  }
}

The module must be called, even if it’s a root-module. (root-module is not a module.)

# The module must be called `main`.
module "main" {
  source = "../.."
  # Variables are not passed from here to the use module.
  text   = "Will not be passed to the used module!"
}

Variables can’t be passed as you may expect. (See “limitation-2”.)

Now you can start testing by using the test_assertions resource.

resource "test_assertions" "my_local_file" {
  component = "my_file_checks"

  check "my_check_if_file_exists" {
    description = "The file exists."
    condition   = fileexists("foo.bar")
  }

  check "my_check_if_file_contains_pattern" {
    description = "The file contains a specific pattern"
    condition   = file("foo.bar") == "Hello world!"
  }
}

In the example above, the two tests basically have a dependency:

One can argue that all test must always run, so no dependency exists.

Demo

A generic example.

The order differs from the documentation; terraform test should apply, but it does not. See “limitation-3”.

Assignment

In case your code fails, the resources are destroyed. Would have been nice to inspect the (faulty) resources before they are cleaned up. See “limitation-4”. On top of that output or resource "local_file" (To drop a file with some data) are not allowed or working. See “limitation-5”.

Limitations