Terraform
Plan Checks
During the Lifecycle (config) and Refresh modes of a TestStep
, the testing framework will run terraform plan
before and after certain operations. For example, the Lifecycle (config) mode will run a plan before the terraform apply
phase, as well as a plan before and after the terraform refresh
phase.
These terraform plan
operations results in a plan file and can be represented by this JSON format.
A plan check is a test assertion that inspects the plan file at a specific phase during the current testing mode. Multiple plan checks can be run at each defined phase, all assertion errors returned are aggregated, reported as a test failure, and all test cleanup logic is executed.
- Available plan phases for Lifecycle (config) mode are defined in the
TestStep.ConfigPlanChecks
struct - Available plan phases for Refresh mode are defined in the
TestStep.RefreshPlanChecks
struct - Import mode currently does not run any plan operations, and therefore does not support plan checks.
Refer to:
- General Plan Checks for built-in general purpose plan checks.
- Resource Plan Checks for built-in managed resource and data source plan checks.
- Output Plan Checks for built-in output-related plan checks.
- Custom Plan Checks for defining bespoke plan checks.
General Plan Checks
The terraform-plugin-testing
module provides a package plancheck
with built-in general plan checks for common use-cases:
Check | Description |
---|---|
plancheck.ExpectEmptyPlan() | Asserts the entire plan has no operations for apply. |
plancheck.ExpectNonEmptyPlan() | Asserts the entire plan contains at least one operation for apply. |
Examples using plancheck.ExpectEmptyPlan
One of the built-in plan checks, plancheck.ExpectEmptyPlan
, is useful for determining a plan is a no-op prior to, for instance, the terraform apply
phase.
Given the following example with the random provider, we have written a test that asserts that random_string.one
will be destroyed and re-created when the length
attribute is changed:
func Test_Random_EmptyPlan(t *testing.T) {
t.Parallel()
r.Test(t, r.TestCase{
ExternalProviders: map[string]r.ExternalProvider{
"random": {
Source: "registry.terraform.io/hashicorp/random",
},
},
Steps: []r.TestStep{
{
Config: `resource "random_string" "one" {
length = 16
}`,
},
{
Config: `resource "random_string" "one" {
length = 16
}`,
ConfigPlanChecks: r.ConfigPlanChecks{
PreApply: []plancheck.PlanCheck{
plancheck.ExpectEmptyPlan(),
},
},
},
},
})
}