Search code examples
terraformdevopsopen-sourceinfrastructure-as-codehashicorp

In Terraform, how do I run a specific *.tf file in a directory?


Using Terraform 0.12.6

I have a directory with multiple *.tf files, e.g., product1.tf, product2.tf etc. How can I execute terraform plan and subsequently terraform apply for a certain *.tf file? I was hoping it would be the -target option but I read the docs and didn't see this mentioned.


Solution

  • You can't. Terraform concatenates all the .tf files in a directory and works on them all at once.

    You can use -target to target specific resources but it has no idea what file they're all in.

    -target in general should be used sparingly as an escape hatch, if you need to run separate bits of Terraform at a time then split your Terraform code up into separate directories and state files.

    This is also discussed in the docs:

    This targeting capability is provided for exceptional circumstances, such as recovering from mistakes or working around Terraform limitations. It is not recommended to use -target for routine operations, since this can lead to undetected configuration drift and confusion about how the true state of resources relates to configuration.

    Instead of using -target as a means to operate on isolated portions of very large configurations, prefer instead to break large configurations into several smaller configurations that can each be independently applied. Data sources can be used to access information about resources created in other configurations, allowing a complex system architecture to be broken down into more manageable parts that can be updated independently.