terraformhcl

Using a single vars file for all modules


I want to arrange my resources in separate directories like modules e.g.

.
├── alb/
├── networking/
├── variables.tf
└── servers/

When I run the terraform validate command from within any of the directory, there is error saying that the variable(s) not declared.

I don't want to keep variables in every directory. What should I do?


Solution

  • You don't run terraform validate in each of those directories (unless you're doing this from your workstation only). You run it at the top level directory, which has passed the appropriate variables to the module blocks.

    Generally speaking (and best practice) is to publish your modules to their own repos (or some other module hosting, e.g.: tf enterprise) and set up a pipeline to run terraform validate as a step/stage/job/whatever. Once it has completed a successful pipeline run, then you can merge and tag it.

    Then you can rest assured that your calling terraform can call those modules, (hopefully by specific versions) knowing there aren't any errors.

    If you're just learning terraform, then the chances you're doing this on your local workstation seems high - if I were you, I'd do something like validate.sh:

    #!/bin/bash
    
    for dir in $(ls -d */); do
        pushd $dir
        echo -e "\n\n$dir\n\n"
        terraform validate
        popd
    done
    
    echo "*****"
    pwd
    echo -e "\n"
    terraform validate