這篇文章將會說明如何快速在 Google Cloud Platform 上使用 Terraform 建立外部和內部的區域 IP 。
定義 GCP Provider 和所需的 Terraform 版本。
terraform {
required_providers {
google = {
source = "hashicorp/google"
version = ">=4.0"
}
}
}
provider "google" {
project = "project-id"
region = "asia-east1"
}
在此檔案中定義外部和內部 IP 地址資源。
resource "google_compute_address" "external_ip" {
name = "external-region-ip"
region = "asia-east1"
address_type = "EXTERNAL"
network_tier = "PREMIUM"
labels = {
"dept" = "devops",
"env" = "dev",
"type" = "external"
}
}
resource "google_compute_address" "internal_ip" {
name = "internal-region-ip"
region = "asia-east1"
address_type = "INTERNAL"
subnetwork = "default"
ip = "10.140.0.5"
labels = {
"dept" = "devops",
"env" = "dev",
"type" = "internal"
}
}
參數介紹
terraform init
terraform plan
terraform apply
resource "google_compute_address" "internal_ip" {
name = var.name
region = var.region
address_type = var.address_type
subnetwork = var.subnetwork
address = var.address
labels = var.labels
}
觀察一下哪些欄位是經常替換的,將經常變更的欄位提取為變數以提高靈活性
variable "name" {
description = "The name of the resource"
type = string
}
variable "region" {
description = "The region of the resource"
type = string
}
variable "address_type" {
description = "The address type"
type = string
}
variable "subnetwork" {
description = "The subnetwork"
type = string
}
variable "address" {
description = "The IP address"
type = string
}
variable "labels" {
description = "The labels for the resource"
type = map(string)
}
建立名為 compute_address的資料夾並建立一份 module.tf
module "google_compute_address" {
source = "../"
name = "internal-region-ip"
region = "asia-east1"
address_type = "EXTERNAL"
subnetwork = "default"
address = "10.140.0.5"
labels = {
"dept" = "devops",
"env" = "dev",
"type" = "internal"
}
}
source的部分會去套用到上一層的 main.tf裡,並使用定義好的變數
進入到compute_address 資料夾進行部署
部署完成後,如果需要清理資源,可執行:
terraform destroy