Terraform Chdir

When working on multiple Terraform projects or switching between configurations in different directories, navigating to the correct working directory can be cumbersome. The terraform -chdir flag simplifies this by allowing you to execute Terraform commands in a different directory without leaving your current one.

Why Use terraform -chdir?

  • To streamline workflows when managing multiple configurations.
  • To execute Terraform commands in a specific directory without navigating there manually.
  • To integrate easily with scripts and automation tools.

How to Use It?

  • To execute a command in another directory: Use terraform -chdir=<directory> <command>. Replace <directory> with the target directory and <command> with the Terraform operation you want to run.
  • To run multiple commands in the same directory: Use -chdir with each command as needed.

Example: Running Commands in a Different Directory

Suppose you have two Terraform configurations, one in project1/ and another in project2/. You’re currently in the root directory but want to initialize the project1 directory.

Instead of navigating to project1/ and running terraform init, use:

terraform -chdir=project1 init

The output will show:

Initializing the backend...
Initializing provider plugins...
Terraform has been successfully initialized!

You can then plan the infrastructure in project2 without changing directories:

terraform -chdir=project2 plan

Output:

Terraform will perform the following actions:
  Plan: 2 to add, 0 to change, 0 to destroy.

Use Case

Imagine you’re managing multiple environments (e.g., dev, staging, prod) stored in separate directories. Using terraform -chdir, you can switch between these environments quickly without leaving your current working directory, saving time and reducing context switching.

Conclusion

The terraform -chdir flag is a simple yet powerful way to streamline your workflow when working with multiple configurations. By allowing you to execute commands in different directories effortlessly, it keeps your operations efficient and organized.