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.
terraform -chdir=<directory> <command>
. Replace <directory>
with the target directory and <command>
with the Terraform operation you want to run.-chdir
with each command as needed.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.
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.
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.