Build Infrastructure with Terraform on Google Cloud
Published: 2024-04-19 16:39:01

TASK TO BE DONE:
Task 1. Create the configuration files
Task 2. Import infrastructure
Task 3. Configure a remote backend
Task 4. Modify and update infrastructure
Task 5. Destroy resources
Task 6. Use a module from the Registry
Task 7. Configure a firewall


**Task 1. Create the configuration files**

main.tf
variables.tf
modules/
└── instances
    ├── instances.tf
    ├── outputs.tf
    └── variables.tf
└── storage
    ├── storage.tf
    ├── outputs.tf
    └── variables.tf

_Step 1:_

Run:  
mkdir -p modules/storage modules/instances


Run: 
touch modules/instances/variables.tf modules/instances/outputs.tf modules/instances/instances.tf modules/storage/variables.tf modules/storage/outputs.tf modules/storage/storage.tf


Run: 
touch main.tf outputs.tf variables.tf


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/28v9474gqutjt9hfzhfd.png)


Then in your **main.tf**:

```
terraform {
  required_providers {
    google = {
      source = "hashicorp/google"
      
    }
  }
}

provider "google" {

  project = var.project_id
  region  = var.region
  zone    = var.zone
}

```

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/xej6wxstl4mn4muiidg7.png)

In all your **variables.tf** files:

```
Variable “zone” {
	Default = ”ZONE”
}

Variable “project_id” {
	Default = ”PROJECT_ID”
}

Variable “region” {
	Default = ”REGION”
}


```
**NOTE:**
To be added in the VARIABLES.TF in the root, instances.tf and storage.tf


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/khf1iq22nwbes0onpk5m.png)

Then run: 

```
terraform init
```


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/olvp9ivhxy7pmd75nwyw.png)

**Task 2. Import Terraform configuration**

_Step 1:_
STEPS IN CREATING VMs

Navigate to Google Cloud Console

- Select or Create a Project: if you haven't already, create a new project or select an existing project where you want to create your compute instances
- Navigate to Compute Engine: in the Google Cloud Console, navigate to the Compute Engine section. You can find it in the left sidebar under the "Compute" section.
- Create a New Instance: click on the "Create" button to create a new virtual machine instance.
- Configure Instance Details: fill out the necessary details for your instance, including:

1. Instance name: Give your instance a descriptive name.
2. Region and Zone: Choose the region and availability zone where you want to deploy your instance.
3. Machine type: Select the machine type that suits your requirements, such as CPU and memory specifications.
4. Boot disk: Choose the operating system and disk size for the boot disk.
5. Networking: Configure network settings such as VPC network, subnetwork, external IP address, and firewall rules.
6. Advanced Configuration (Optional): you can also configure additional options such as GPU, metadata, and startup scripts if needed.

- Review and Create: review the configuration of your instance to ensure everything is correct. 
- Once you're satisfied, click the "Create" button to provision the instance.

Repeat to create another instance. We’re creating the instances so we can import them later into our terraform configuration and terraform can be responsible for managing them.

_Step 2:_
In your instance.tf: 

```
resource "google_compute_instance" "INSTANCE_NAME-1" {
  name         = "tf-instance-1"
  machine_type = "e2-micro"
  zone         = var.zone

  boot_disk {
    initialize_params {
      image = "debian-cloud/debian-11"
      Size = “10”
    }
  }

  network_interface {
    network = "default"
 
  }
}


resource "google_compute_instance" "INSTANCE_NAME-2" {
  name         = "tf-instance-2"
  machine_type = "e2-micro"
  zone         = var.zone

  boot_disk {
    initialize_params {
      image = "debian-cloud/debian-11"
      Size = “10”
    }
  }

  network_interface {
    network = "default"
 
  }
}

```

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/t5hjqbq8j30d6434upld.png)

Then add the following to your main.tf:

```
module “instances”{
	source = “./modules/instances”
}
```


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/al75hppqvvpc410vu36a.png)

Then run: 

```
terraform init
```


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/kachd8z3tps3nlsqtavv.png)

Next:
Run this command: 

```
terraform import module.instances.google_compute_instance.INSTANCE_NAME-1 INSTANCE_ID
```

Then:

```
terraform import module.instances.google_compute_instance.INSTANCE_NAME-2 INSTANCE_ID
```


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/cgss67j7o890y808ar2n.png)

**NOTE:** INSTANCE_ID can be gotten from the console.


Task 3. Configure a remote backend

In your storage.tf file add the following

```
resource "google_storage_bucket" "STORAGE_BUCKET" {
  name        = "# REPLACE WITH YOUR PROJECT ID"
  location    = "US"
  uniform_bucket_level_access = true
  Force_destroy = true }

```

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/71veck5hksy88swl4xnm.png)

Then add the following to your main.tf file:
	

```
module “compute_storage”{
		source = “./modules/storage”
}

```

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/s3x3feo0vb8vyds586t8.png)

Then run: 

```
terraform init
```


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/9luz9z2gnpgsut01s38x.png)

Then run:

```
terraform apply
```


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/qsi8nsf1xcbeap4eow74.png)

After the bucket is created add the following to your main.tf in the terraform block

 

```
 backend "gcs" {
    bucket  = "# REPLACE WITH YOUR BUCKET NAME"
    prefix  = "terraform/state"
  }
```


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/6u72o5xly86r5ico62i3.png)

Run:

```
terraform init 
```

It should prompt you, type yes 


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/fgdgfkvkag85a8hp4t39.png)



**Task 4**

_To update infrastructure:_

You only need to change machine-type argument from “e2-micro” to the type provided. This should be done in your **instances.tf**  file

The add a new instance resource in the same file

```
resource "google_compute_instance" "THIRD INSTANCE NAME" {
  name         = "THIRD INSTANCE NAME"
  machine_type = "SPECIFIED MACHINE TYPE"
  zone         = var.zone

  boot_disk {
    initialize_params {
      image = "debian-cloud/debian-11"
      Size = “10”
    }
  }

  network_interface {
    network = "default"
 
  }
}

```

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/3bya5q9hzm4vj9iebpkq.png)

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/312r62ddstfzt1xmewmc.png)

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/dcjenf1cxyv8gsdlbwjk.png)

Then run: 

```
terraform init
```


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/i42w604va31gfu3974eg.png)

Then: 

```
terraform apply 
```


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/qns1mk5vlkoygekvyeq0.png)


**Task 5**

To delete resource: You just remove the third instance configuration from your **instances.tf**  file and then run 

```
terraform apply
```


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/bq6445rkxid4wugq4zhr.png)


**Task 6**
Add to your **main.tf file**

```
module "vpc" {
source  = "terraform-google-modules/network/google"
version = "9.0.0"
project_id   = "<PROJECT ID>"
network_name = "VPC_NAME"
routing_mode = "GLOBAL"
	subnets = [
        {
            subnet_name           = "subnet-01"
            subnet_ip             = "IP_RANGE"
            subnet_region         = var.region
        },
	{
            subnet_name           = "subnet-02"
            subnet_ip             = "IP_RANGE"
            subnet_region         = var.region
        },

]


}
```


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/1hvqxgi5d9zabz1ezmfs.png)

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/zognvurew052vyfc3703.png)

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/tocr08efa5ho4cj9vx8w.png)


After adding the block, run:

```
terraform init 
```


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/aj7rp6k07vy0sxl26xjk.png)

Then run:

```
terraform apply
```


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/50pwhrbimnzl98w8elyq.png)


**Task 7**

Add to your **main.tf file**:

```
resource “google_compute_firewal”l “FIREWALL_NAME”{
	name = “FIREWALL_NAME”
	network = module.vpc.network_name

	allow {
    protocol = "tcp"
    ports    = ["80"]
  }
	source_ranges = [0.0.0.0/0]
}


```

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/4n9s2pzoj2g2xo4xwj70.png)

run : 

```
terraform init 
```


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/4yiycy7rz90gvqfyebwb.png)

then : 

```
terraform apply
```


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/95yefzf7zwbsj9lv7txu.png)

Update the **instance.tf** file to use the newly created VPC and place each instance in a different subnet


```
resource "google_compute_instance" "INSTANCE_NAME-1" {
  name         = "tf-instance-1"
  machine_type = "e2-micro"
  zone         = var.zone

  boot_disk {
    initialize_params {
      image = "debian-cloud/debian-11"
      size = “10”
    }
  }

  network_interface {
    network = "VPC_NAME"
    subnetwork = “SUBNET_1”
 
  }
}


resource "google_compute_instance" "INSTANCE_NAME-2" {
  name         = "tf-instance-2"
  machine_type = "e2-micro"
  zone         = var.zone

  boot_disk {
    initialize_params {
      image = "debian-cloud/debian-11"
      size = “10”
    }
  }

  network_interface {
    network = "VPC_NAME"
    subnetwork = “SUBNET_2” 
 
  }
}


```