DEV Community

eidher
eidher

Posted on • Updated on

Automating the Deployment of Infrastructure in Google Cloud Using Terraform

Google Cloud has its own Deployment Manager. However, some people are more habituated to Terraform. Terraform is now integrated into Cloud Shell. At this moment it includes Terraform v0.12.24.

In this example, we are going to create a VPC network, a firewall rule to allow HTTP, SSH, RDP, and ICMP traffic on the network. And two Compute Engine VM instances.

First, we need to define the provider:

provider "google" {}
Enter fullscreen mode Exit fullscreen mode

Now, we define two resources (the google_compute_network resource is a VPC network, then we have the firewall rule) and two modules (VM instances):

resource "google_compute_network" "mynetwork" {
  name                    = "mynetwork"
  auto_create_subnetworks = true
}

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"
  }
}

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

module "mynet-eu-vm" {
  source           = "./instance"
  instance_name    = "mynet-eu-vm"
  instance_zone    = "europe-west1-d"
  instance_network = google_compute_network.mynetwork.self_link
}
Enter fullscreen mode Exit fullscreen mode

Let's see the main.tf file. Here we have a google_compute_instance resource (which properties are applied to the Compute Engine instances) and four input variables with default values (optional)

variable "instance_name" {}
variable "instance_zone" {}
variable "instance_type" {
  default = "n1-standard-1"
  }
variable "instance_network" {}

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-9"
      }
  }
  network_interface {
    network = "${var.instance_network}"
    access_config {
      # Allocate a one-to-one NAT IP to the instance
    }
  }
}
Enter fullscreen mode Exit fullscreen mode

Finally, execute the Terraform commands where we have the tf files:

terraform init
terraform plan
terraform apply
Enter fullscreen mode Exit fullscreen mode

View source code:

Top comments (0)