Skip to main content

Learn any cloudTerraform LearnLabsTerraform validate, step by step

Terraform validate, step by step

WorkspacesUnknown

Start from a small root that passes, see what terraform init -backend=false, terraform fmt -check and terraform validate each check, break it three different ways to learn which command catches which mistake, and find out why init works here with no registry at all.

Introductoryabout 20 minutesToolsterraform

Opening your lab workspace…

Steps

  1. Step 1: Read the root

    The folder holds one file, main.tf: two providers (hashicorp/azurerm and hashicorp/random), one random_pet resource and no backend. Read the comment at the top; it says what a passing init here proves.

  2. Step 2: Initialise with no registry

    terraform init -backend=false
    

    It completes, and nothing was downloaded. The image sets TF_CLI_CONFIG_FILE to a configuration that installs providers from a filesystem mirror. Look at both:

    cat "$TF_CLI_CONFIG_FILE"
    ls /opt/terraform/mirror/registry.terraform.io/hashicorp
    

    Every provider listed there can be installed offline; that is how the lab runner validates with the network switched off.

  3. Step 3: fmt, then validate

    terraform fmt -check -diff
    terraform validate
    

    Both pass. Now indent the length line in main.tf by one extra space and run both again: fmt -check reports the file and exits non-zero, validate still passes. Formatting is not correctness. Run terraform fmt with no flags to fix it.

  4. Step 4: Break a reference

    Add an output that points at a resource that does not exist:

    output "pet" {
      value = random_pet.smokey.id
    }
    

    terraform fmt -check is happy; terraform validate is not, and it names main.tf, the line and the undeclared resource. Change smokey to smoke and validate again.

  5. Step 5: Ask for a provider the mirror lacks

    Add aws = { source = "hashicorp/aws", version = "~> 6.0" } to required_providers and run terraform init -backend=false. It fails before validate can run: the mirror has no hashicorp/aws, and the configuration allows no other source. This is the runner’s answer too, by design. In this workspace you may reach the registry for one command:

    TF_CLI_CONFIG_FILE=/dev/null terraform init -backend=false
    

    Then remove the aws block again, delete .terraform.lock.hcl, and re-run the offline init.

  6. Step 6: What none of the three can tell you

    A root that inits, formats and validates can still fail to plan: azurerm needs credentials to plan anything, a name may be taken, a quota may be full. Those are plan-time and apply-time facts, and this lab stops before them on purpose. To see the runner reach the same verdict on your main.tf, send it as a terraform-validate job.

    Checked by the agent (terraform-validate): Paste main.tf as the text payload: the runner inits it with no network from the same mirror and prints what terraform validate said.