A Terraform Module Contract Must Survive Both Forms and Agents

·

11 min read

A developer form and an AI assistant can submit the same apparently reasonable request while making different assumptions about its meaning. One may send an empty owner field. Another may invent an environment name. Both may treat a replica count as a preference even when the platform treats it as an operational requirement.

A Terraform module is a useful place to make those assumptions executable. Its input contract can describe valid shapes and values independently of the interface that collected them. The interface improves the interaction; the module decides which requests it accepts.

The design challenge is to avoid replacing one undocumented convention with another. A type declaration alone does not explain every valid combination, and a collection of happy-path tests does not establish what happens when an agent supplies an unexpected request. The strongest contract combines a small input surface, explicit invariants and tests that preserve those invariants across module revisions.

A contract has more than a type

Terraform input variables support type constraints, nullability and validation rules. These mechanisms were present in the version-pinned reference used for this study. They can reject structurally invalid or semantically unacceptable inputs before a proposed configuration progresses through its normal workflow. Terraform 1.10.5 variables, release date.

A number is a type. A positive whole-number replica count is a requirement. A string is a type. A nonempty ownership identifier with an established governance meaning is a requirement. The second statement in each pair needs additional rules.

Relationships between values are another layer. A development workload may accept one replica while production requires at least two. A form can express that relationship interactively, but a caller can bypass the form. Keeping the invariant in the module gives alternate consumers the same acceptance boundary.

That boundary should remain narrow enough to explain. If every possible platform preference becomes a variable, the module becomes a general-purpose interpreter for organizational policy. A smaller contract with explicit extension points is easier to document, test and preserve.

A complete providerless contract

The example below represents a deployment request without creating a cloud resource. The output exposes the accepted value so that plan-only tests can examine the contract directly.

terraform {
  required_version = "= 1.10.5"
}

variable "request" {
  type = object({
    environment = string
    replicas    = number
    owner       = string
  })
  nullable = false

  validation {
    condition     = contains(["dev", "prod"], var.request.environment)
    error_message = "environment must be dev or prod."
  }

  validation {
    condition = (
      var.request.replicas == floor(var.request.replicas) &&
      var.request.replicas >= 1 &&
      var.request.replicas <= 6
    )
    error_message = "replicas must be an integer from 1 through 6."
  }

  validation {
    condition     = var.request.environment != "prod" || var.request.replicas >= 2
    error_message = "production needs at least two replicas."
  }

  validation {
    condition     = length(trimspace(var.request.owner)) > 0
    error_message = "owner must contain non-whitespace text."
  }
}

output "contract" {
  value = var.request
}

These are original study requirements, not universal infrastructure rules. Two production replicas do not prove availability, and a nonblank owner does not prove that the named team exists. The example isolates what this module can actually validate.

Grouping the inputs into one request object makes the relationship between environment and replicas local to the same value. The referenced Terraform version also supports broader cross-variable validation, but this study does not require that capability. The historical custom-condition documentation distinguishes variable validation from resource preconditions, postconditions and checks. Tagged custom conditions.

The distinction helps prevent an overloaded contract. A rule about the request belongs near the input. A rule about a provider's resolved result may need a later validation point. Moving an observation-dependent condition into an input rule does not make the observation available earlier.

Test the rejected requests

Terraform's testing framework was available from version 1.6. The pinned documentation describes plan and apply test runs, with apply as the default. The tests here explicitly choose plan so that the study evaluates the contract without creating infrastructure. Version-pinned tests.

One positive and one negative test demonstrate the structure:

run "production_contract" {
  command = plan
  variables {
    request = {
      environment = "prod"
      replicas    = 2
      owner       = "platform"
    }
  }
  assert {
    condition     = output.contract.owner == "platform"
    error_message = "Owner was not preserved."
  }
}

run "reject_production_singleton" {
  command = plan
  variables {
    request = {
      environment = "prod"
      replicas    = 1
      owner       = "platform"
    }
  }
  expect_failures = [var.request]
}

The complete packaged suite contains seven cases. Development with one replica and production with two were accepted. An unknown environment, a production singleton, a fractional count, a blank owner and a count above the study limit were rejected as expected. All seven tests passed on Terraform 1.10.5.

The negative test is successful because the invalid request fails. That inversion deserves explicit attention in CI reporting. A test runner's green result describes the expected behavior of the contract; it does not mean that every supplied request would be accepted for deployment.

The suite is deliberately modest. It does not establish cloud behavior, organizational identity validation or production availability. Its value is a reproducible statement about a particular module interface and the inputs that interface accepts.

Keep the test oracle independent

A form generated from the module and an agent prompt generated from the same description can share useful terminology. They can also share the same missing rule. Deriving every test from the generated interface risks preserving that omission.

The acceptance cases should therefore come from the platform's declared requirements. The production singleton is a particularly useful counterexample: its individual values satisfy their types and basic ranges, but their combination violates the intended operating rule.

Changes to expected outcomes need explicit review. If a module revision fails a previously accepted request, changing the test to match the new behavior is a contract decision. It should not be disguised as routine test maintenance.

An AI assistant can help enumerate boundary cases, but the resulting cases still need a reason. “The model suggested this input” is weaker evidence than “this input exercises the lower production bound.” The latter remains useful even when the generation tool changes.

A module contract is checked before deployment

Reference design. Both callers reach the same module validation boundary; interface validation improves feedback but does not replace it.

Error messages are part of developer experience

A validation failure should explain the violated invariant with enough precision to support correction. The example names the permitted environments and replica limits. It does not ask the caller to infer a rule from a generic execution failure.

That clarity helps both humans and agents. A human can correct the request without examining module internals. An agent can produce a revised proposal whose change is small and reviewable. Neither consumer needs permission to modify the contract merely because its first request was rejected.

The platform should preserve the distinction between a validation denial and an execution problem. A malformed request needs a corrected input. A provider authentication failure needs operational investigation. An interface that collapses both into “deployment failed” encourages inappropriate retries and makes the module feel unreliable.

Error handling can also leak context. Validation messages should describe the relevant requirement without echoing unnecessary secrets or internal policy detail. A useful diagnostic is specific about the violated rule, not indiscriminately verbose about the submitted object.

Defaults carry authority

A default is not neutral. It selects behavior when a caller omits a value. That may be convenient for a development request and dangerous for an environment, ownership or exposure decision.

A proposed platform contract should classify defaults by consequence. Some defaults are ergonomic choices with limited operational impact. Others encode a decision that requires an accountable owner. The module should not silently supply the latter merely to make a form shorter or an agent call easier.

Default changes also affect reproducibility. Two requests with identical visible input can resolve differently after a module update if omitted values receive new defaults. A review record should therefore include the selected module revision and the resolved contract, not only the user's original fields.

The same reasoning applies to normalization. Trimming whitespace might improve an identifier, while lowercasing a value could change a case-sensitive external name. Normalization needs a documented purpose and tests; it should not be an accidental convenience embedded in several consumers.

Evolving the interface without surprise

A module contract is an API even when its callers are other Terraform configurations. Adding a required input, tightening an accepted range or changing an output's meaning can break existing consumers without changing the resource type names.

A compatibility review should compare the old and new input domains. Which previously accepted requests now fail? Which previously rejected requests now succeed? Does a default resolve differently? Do outputs retain their shape and meaning?

This analysis is separate from checking whether the new module validates in isolation. A syntactically valid module can still be incompatible with the existing catalogue of requests. Retaining representative fixtures from real supported use cases gives the review something concrete to compare.

The contract should also define what it intentionally does not promise. The example validates a request object. It does not promise the continued existence of a cloud instance, the membership of the owner team or a service-level objective. Those properties belong to other checks with their own evidence.

Avoid turning tests into accidental deployments

The testing framework supports real infrastructure operations, which can be valuable for integration verification. That capability also means a test suite deserves an execution policy. The explicit plan command in this study is a deliberate limit, not a universal claim that Terraform tests are side-effect free.

A production module may invoke providers or data sources even during planning. Credential scope, network access and test-account isolation therefore require review for the actual module under test. The providerless example avoids those integration dependencies; it does not demonstrate their safe configuration.

Test cleanup is another responsibility when apply-based tests are used. A successful assertion does not guarantee that every later teardown operation succeeds. A platform needs visibility into residual resources and the authority required to remove them.

The right sequence is to use cheap contract tests for fast feedback, then add a smaller set of integration checks for properties that require actual provider behavior. Each layer should state what it proves rather than borrowing confidence from the other.

State the limits of input validation

The laboratory uses concrete values supplied before planning. A more complex module can receive values derived from other resources, which changes when a condition can be evaluated. An interface should distinguish a condition that passed from one whose required information is not yet available. Treating deferred evaluation as acceptance would make the review record stronger than the evidence.

Nullability also deserves tests at the actual boundary. The example rejects a null request object, but that statement is not a claim that every possible nested null or malformed provider response has been exercised. The seven fixtures establish their listed cases. A production extension should add explicit handling for nullable nested attributes before applying functions that require a valid number or string.

This limitation is useful because it identifies the next test, rather than hiding it behind a broad validation claim. The same approach applies to extremely large values, unsupported fields and alternate encodings introduced by a calling interface. Each supported input category should have a deliberate normalization or rejection rule.

An agent-facing schema can document these categories, but it remains a convenience contract at a different boundary. The adapter should verify the request it actually passes to Terraform, and the module should retain its own rules. A change to either side needs compatibility checks against the shared acceptance corpus.

One acceptance boundary, several experiences

A portal can offer guided choices, an editor can provide local feedback, and an assistant can explain the consequences of a request. Those experiences do not need identical interfaces. They need a shared definition of an acceptable request.

The module contract provides that stable reference when its requirements are explicit, its versions are recorded and its rejection cases are preserved. The surrounding platform can then improve convenience without weakening the underlying constraint.

The result is a practical form of intelligent orchestration: callers can propose and explain, while deterministic code evaluates the request. Developer experience improves because the rules become discoverable and testable, not because invalid requests are quietly made executable.