Vidya
Vidya

Reputation: 657

Terraform main.tf to differnt name convention

Is it possible to use diffent name other than main.tf in terraform

I have two main.tf files, one for tfstate execution and another for project execution. I am planning to keep both in same level directory and call something like

terraform init/plan/apply -main-file=tfstate.tf
terraform init/plan/apply -main-file=project.tf

I checked https://www.terraform.io/docs/cli/commands/plan.html, I did not find any option

Upvotes: 1

Views: 2493

Answers (3)

avinava basu
avinava basu

Reputation: 147

Long story short, Yes you can name your main files with any prefix. Eg: Let's say you are creating two resources inside one directory.

  • VPC
  • EC2

You can name them vpc.tf and ec2.tf along with other files like terraform.tfvars, variables.tf, data.tf , outputs.tf etc.

Essentially it reads everything after the . extension and builds the entire thing within the directory.

Upvotes: 0

Martin Atkins
Martin Atkins

Reputation: 74299

In Terraform the names of individual files are not significant and instead Terraform works with whole directories.

To achieve the result you are describing you should put your separate .tf files in different directories. You can then either switch to each directory in turn to run terraform apply, or you can use the -chdir global option to ask Terraform to switch directory itself before running the apply operation:

  • terraform -chdir=tfstate apply for the .tf files in the subdirectory tfstate
  • terraform -chdir=project apply for the .tf files in the subdirectory project

Terraform always works with an entire directory at once, so there is no way to tell Terraform to look at only one file at a time. The filename main.tf is not special to Terraform and is just a convention commonly used for simple modules that only need one file.

Upvotes: 1

bembas
bembas

Reputation: 771

The best practice that Terraform suggest is to use the workspaces.

Terraform has a default name workspace if you haven't create one. This workspace is special both because it is the default and also because it cannot ever be deleted.

You can create a new one with the command :

terraform workspace new dev

For listing :

terraform workspace list

For switching workspaces:

terraform workspace select dev

Upvotes: 2

Related Questions