Terraform Test - Module Source Path

Hi all

I am trying to understand how Terraform Test find and load the module inside the run block. In specific for scenario where the .test.hcl file is not located in the root or in the ./tests directory.

My setup

I have unique requirement in my CI/CD pipeline where I have to put the test file on separate directory under the root, let’s call it ./functional-tests.

My module structure resemble something like below (simplified):

├── main.tf
└── examples
    ├── basic
        ├── main.tf
└── functional-tests
    ├── basic.tftest.hcl

My test file is as follow:

run "mandatory_apply_basic" {
# call the examples/basic to test the examples
  command = apply
  module {
    source = "./examples/basic"
  }
}

And I run the terraform test as follow:

terraform test -test-directory=./functional-test

Problem

Terraform test always complaining that the module was not initialized, despite I have initialized terraform init both on the root and also on the ./examples/basic directory.

This problem disappear as soon as I moved the test file to the default directory ./tests. For example:

├── main.tf
└── examples
    ├── basic
        ├── main.tf
└── tests
    ├── basic.tftest.hcl

This makes me think that there are certain limitation or pre-requisite before I could use different directory to run the tests file?

Hi @wellsiau, terraform init also supports the -test-directory flag (or at least it should and is a bug if it doesn’t). This should work for you if you specify the same test directory during initialisation as you do while testing.

It’s not recommended to use a non-standard test directory, but I note that you did say it’s required for your use case. If you are using multiple test directories, you’ll need to run a dedicated initialise step before executing the test command for every test directory within your configuration.

Hope that makes sense and it works!

1 Like

@liamcervante , thank you for your reply.

For now, we made concession by moving all the tests into the ./tests directory.

I wasn’t aware about the -test-directory flag and will certainly test it when time permit.

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.