Terraform


Terraform is an infrastructure as code tool that enables you to safely and predictably provision and manage infrastructure in any cloud.


You do not need to name files as main.tf, variables.tf, or outputs.tf specifically. Terraform reads all .tf files in a directory, regardless of their names, and merges the configuration to form a unified plan. A good practice is to use these descriptive names so it makes easier for others to understand the structure of your Terraform setup.

For each module block, Terraform will navigate to the path specified in the source parameter or fetch the module from a remote source (like Terraform Registry or Git). Inside the module directory, Terraform looks for .tf files just like it does in the root directory. It loads and processes them similarly to construct resources and outputs. If the modules define their own variables, Terraform expects you to provide values either directly or via variable blocks


Once all .tf files are loaded, Terraform merges the content to build a resource dependency graph

➜  infra git:(main) ✗ cat mynetwork.tf
# Create the mynetwork network
resource "google_compute_network" "mynetwork" {
  name = "mynetwork"
  # RESOURCE properties go here
  auto_create_subnetworks = "true"
}
# Add a firewall rule to allow HTTP, SSH, RDP and ICMP traffic on mynetwork
resource "google_compute_firewall" "mynetwork-allow-http-ssh-rdp-icmp" {
  name = "mynetwork-allow-http-ssh-rdp-icmp"
  # RESOURCE properties go here
  network = google_compute_network.mynetwork.self_link
  allow {
    protocol = "tcp"
    ports    = ["22", "80", "3389"]
  }
  allow {
    protocol = "icmp"
  }
  source_ranges = ["0.0.0.0/0"]
}
# Create the mynet-vm-1 instance
module "mynet-vm-1" {
  source           = "./instance"
  instance_name    = "mynet-vm-1"
  instance_zone    = "us-east1-d"
  instance_network = google_compute_network.mynetwork.self_link
}
# Create the mynet-vm-2" instance
module "mynet-vm-2" {
  source           = "./instance"
  instance_name    = "mynet-vm-2"
  instance_zone    = "us-west1-b"
  instance_network = google_compute_network.mynetwork.self_link
}
➜  infra git:(main) ✗ tree
.
├── instance
│   ├── instance.tf
│   └── variables.tf
├── mynetwork.tf
├── provider.tf
└── README.md