This repository provisions a VM instance on Google Cloud Platform using Terraform.
terraform-gcp-vm/
├── main.tf
├── variables.tf
├── modules/
│ └── gcp_vm/
│ ├── main.tf
│ └── variables.tf
- Creates a GCP Compute Engine instance
- Accepts parameters: instance type, zone, image
- Installs nginx via startup script
- Outputs the public IP of the VM
- Terraform v1.3+
- GCP credentials configured via
gcloud auth application-default login
- Clone the repo:
git clone <this-repo>
cd terraform-gcp-vm- Initialize Terraform:
terraform init- Set variables and apply:
terraform apply -var="project_id=your-gcp-project-id" -var="region=us-central1"- After ~30 seconds, you’ll see:
Outputs:
vm_public_ip = "X.X.X.X"
- Visit the VM IP in your browser:
http://X.X.X.X → Should show NGINX welcome page
To test:
- Use
terraform planto verify - Use
terraform destroyto clean up after testing
- Default network is used; ensure "Allow HTTP traffic" is enabled in firewall
- Add SSH access or use IAP as needed
To run the integration test using Terratest:
- Go 1.21+
- Terraform installed
- GCP credentials set up (
gcloud auth application-default login)
cd test
go mod tidy
go test -vThis will be expected to provision a VM, verify NGINX is running, then destroy the VM.
-
Use Service Account for Authentication
- Replace reliance on
gcloud auth application-defaultlogin with a dedicated service account key to improve portability and CI/CD support.
- Replace reliance on
-
Test Enhancements
- Improve test stability by:
- Adding exponential backoff and retry logic
- Making NGINX content check more flexible (use regex or header check)
- Validating instance metadata via
gcloudor GCP APIs
- Improve test stability by:
-
Expose More Config Options
- Add optional inputs for:
- Tags, labels, metadata
- Disk size/type
- Custom startup script
- Add optional inputs for:
-
Support Multiple Instances
- Extend the module to provision a group of VMs using
countorfor_each.
- Extend the module to provision a group of VMs using
-
Add Outputs for Internal IP, Status, and SSH Command
- Provide more useful output for users to interact with the VM.