liveBook · Manning

Go

As explained in Terraform in Depth: Infrastructure as Code with Terraform and OpenTofu

A statically typed compiled programming language designed for general-purpose software development.

Go is a practical way to test Terraform modules with Terratest. Terratest uses Go’s testing package, so tests can also use other Go libraries. The tradeoff is that a team must learn a new language, but module tests can start as small scripts rather than full applications. section 9.3.1

To get a test running:

  • Create a file in the project’s tests directory with a name ending in _test.go. Declare a package, import testing and any other needed packages, then write a test function. section 9.3.1
  • In the tests directory, run go mod init with a module name, commonly a repository path. This creates go.mod. Then run go mod tidy to fetch dependencies and create go.sum. section 9.3.1
  • Run the test and inspect its result. A passing run reports PASS; a failure identifies the test, source line and assertion mismatch. section 9.3.1
Listing 9.6 Example test in Go
package tests                            #1
 
import (
    "testing"                            #2
 
    "github.com/stretchr/testify/assert" #3
)
 
func TestExample(t *testing.T) {         #4
    assert.Equal(t, 1, 1)                #5
}

This small test shows the package declaration, imports, a test function receiving *testing.T, and an assertion supplied by a third-party library. section 9.3.1

Go also appears when moving from Terraform configuration to provider development: install the Go tools first, and consider an IDE extension such as the VSCode Go extension. For an external-provider wrapper program, choose a language with its deployment environment in mind; the portability and maintenance tradeoffs differ from those of a small test. section 12.2 section 10.4.2

How Terraform in Depth: Infrastructure as Code with Terraform and OpenTofu covers it

How deep it goes
Walks through test-file structure, module initialization and test results, but limits the introduction to small tests rather than full Go applications.
Examples
Shows an assertion-based Go test, passing and failing test output, and commands that initialize a module and fetch dependencies.
What it assumes
Starts with a minimal Go testing pattern for developers who may be new to Go; requires Go tools for provider development.
What you can do after
Apply it via Terratest and Go’s testing package to create and run small Terraform-module tests.
How it connects
Connects Go to Terraform modules, Terratest, the Go testing package, third-party libraries and Terraform provider development.

Also explained in

Compare how 11 books explain Go →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Terraform in Depth: Infrastructure as Code with Terraform and OpenTofu. The section links point to the parts of the book it draws on.