[Terraform] Hands on labs with Modules !

LizzyLee·2024년 10월 18일

File Structure

instance > main.tf

resource "google_compute_instance" "vm_instance" {
   name = "${var.instance_name}"
   zone = "${var.instance_zone}"
   machine_type = "${var.instance_type}"

   boot_disk {
     initialize_params {
       image = "debian-cloud/debian-11"
     }
   }

   network_interface {
     network = "${var.instance_network}"
     access_config {
       #  Leaving the access configuration empty results in an ephemeral external IP address 
     }
   }
}

instance > variables.tf

variable "instance_name" {}
variable "instance_zone" {}
variable "instance_type" {
    # By giving instance_type a default value, you make the variable optional. 
    default = "e2-micro"
}
variable "instance_network" {}

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"
  network = google_compute_network.mynetwork.self_link
  allow {
      protocol = "tcp"
      ports    = ["22", "80", "3389"]
      }
  allow {
      protocol = "icmp"
      }
  source_ranges = ["0.0.0.0/0"]
}

module "mynet-vm-1" {
    source = "./instance"
    instance_name = "mynet-vm-1"
    instance_zone = "us-west1-a"
    instance_network = google_compute_network.mynetwork.self_link
}

module "mynet-vm-2" {
    source = "./instance"
    instance_name = "mynet-vm-2"
    instance_zone = "europe-west4-a"
    instance_network = google_compute_network.mynetwork.self_link
}

0개의 댓글