Infra as Code
Introduction
You can make good use of terraform to create file so as to create or manage the cloud resource in declarative way
Here is the docs and templates for creating gcp resource
Operation
Create declarative files for creating resource , here are the examples
# connect to gcp by using provider
provider "google" {
project = var.project_id
region = var.region
}
terraform {
required_providers {
google = {
version = "~> 4.0"
}
}
}
# declare resources
module "network" {
source = "terraform-google-modules/network/google"
version = "~> 4.1.0"
project_id = var.project_id
network_name = "lab03-vpc"
routing_mode = "GLOBAL"
subnets = [
{
subnet_name = "lab03-subnet-01"
subnet_ip = "10.10.10.0/24"
subnet_region = var.region
},
]
secondary_ranges = {
subnet-01 = [
{
range_name = "lab03-secondary-01"
ip_cidr_range = "192.168.64.0/24"
},
]
}
}
module "cloud_nat" {
source = "terraform-google-modules/cloud-nat/google"
version = "~> 2.1.0"
project_id = module.project_iam_bindings.projects[0]
region = var.region
create_router = true
router = "lab03-router"
network = module.network.network_name
}
module "project_iam_bindings" {
source = "terraform-google-modules/iam/google//modules/projects_iam"
version = "~> 7.4.0"
projects = [var.project_id]
mode = "additive"
bindings = {
"roles/cloudfunctions.admin" = [
local.iam_member,
]
"roles/compute.admin" = [
local.iam_member,
]
"roles/compute.networkAdmin" = [
local.iam_member,
]
"roles/iam.serviceAccountAdmin" = [
local.iam_member,
]
"roles/serviceusage.serviceUsageAdmin" = [
local.iam_member,
]
}
}
# declare local file variable
locals {
iam_member = "serviceAccount:sa-cft-training@${var.project_id}.iam.gserviceaccount.com"
}
Declare global variables for multiple resource files
# declare the type of variables
variable "project_id" {
description = "GCP Project ID"
}
variable "region" {
description = "GCP Region"
default = "us-east1"
}
project_id = "my-gcp-id" # Insert Project ID here
Pack the declared modules to output
output "network" {
value = module.network.network_name
}
output "subnets" {
value = module.network.subnets_names
}
output "cloud_nat" {
value = module.cloud_nat.name
}
output "cloud_nat_router" {
value = module.cloud_nat.router_name
}
Migrate the record to cloud storage
terraform {
backend "gcs" {
bucket = "bucket-name" # GCS bucket for Terraform Remote State
prefix = "terraform/state/03/"
}
}
Init the project to install the dependency needed
terraform init
Prepare the execution resources and store into file and check the differences after updated
terraform plan -out plan.out
Apply the execution plan to gcp to create resources
terraform apply plan.out
Delete the updated changes
terraform destroy
Last updated
Was this helpful?