如何使用 Terraform 在 GCP 上建立外部和內部的區域 IP 地址

2023/11/25閱讀時間約 7 分鐘


raw-image

👨‍💻 簡介

這篇文章將會說明如何快速在 Google Cloud Platform 上使用 Terraform 建立外部和內部的區域 IP 。

前提條件

  • Google Cloud Platform (GCP) 帳號: 確保有一個有效的 GCP 帳號。
  • 安裝 Terraform: 還沒安裝可以參考 Terraform 安裝指南 。
  • 基礎 Terraform 知識: 瞭解基本的 Terraform 命令和概念,如果需要,可參考 Terraform 入門指南

🎯setup

1:建立 provider.tf

定義 GCP Provider 和所需的 Terraform 版本。

terraform {
required_providers {
google = {
source = "hashicorp/google"
version = ">=4.0"
}
}
}

provider "google" {
project = "project-id"
region = "asia-east1"
}

2:建立 main.tf

在此檔案中定義外部和內部 IP 地址資源。

  • External 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"
}
}
  • Internal IP
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"
}
}

參數介紹

  • name:ip name
  • region:ip region
  • address_type:建立的網路類型,分為內網 (Internal) 以及外網 (External)
  • network_tier:使用的網路等級,僅限外網使用
  • ip:指定內網 IP
  • labels:使用的 label,有助於資源分類和管理。

3:初始化 Terraform

terraform init

4:執行 Dry Run

terraform plan

5:部署

terraform apply

🛠️模組化

1. 改寫main.tf

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
}

2. 定義變數

觀察一下哪些欄位是經常替換的,將經常變更的欄位提取為變數以提高靈活性

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

3. 模組化

建立名為 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裡,並使用定義好的變數

4. 部署

進入到compute_address 資料夾進行部署

資源刪除

部署完成後,如果需要清理資源,可執行:

terraform destroy

📚Reference

16會員
75內容數
golang
留言0
查看全部
發表第一個留言支持創作者!
從 Google News 追蹤更多 vocus 的最新精選內容