Split Configuration across multiple files

You can (and should) split resources across multiple files (even folders, if you so desire). The entire deployment will have a single state file managing all the resources.

Accessing Resources across files 

When you split resources in such a way (e.g loadbalancer.tf and backend.tf), how do you actually access resources defined in one file from another?

All of this works, because these split configuration files are still part of a single module – the root module.

What if the configuration is split across modules?

You have two options here – simply use the module keyword to access any resources (or output values) in one module from another.

The second option is to use the statefile of the second module – and use IT as a data source! See the sample below:


Define output values in your first file
output “keyversion” {
  value = azurerm_key_vault_key.mykey.version
}

Define the state (state file) of the 1st file as a data source for the second file

data "terraform_remote_state" "firstfile_data" {
  backend = "local"

  config = {
    path = "../my_folders/terraform.tfstate"
  }
}
In your second file, you can retrieve the outputs
locals {
 keyversion = data.terraform_remote_state.firstfile_data.outputs.keyversion
}
Summary
That’s it. Using resources defined in one terraform file from another is easy. The trick is to either use the module keyword – or to use the state file of the first file to retrieve output values – to be used in the second file.