# Terraform tf file 快速建置雲端服務

NYUST GDSC Leads FKT


# 今天主題 Terraform

開發公司: HashiCorp
主要功能:透過文件快速根據需求建置雲端服務


# 基本介紹

Terraform 支援的平台

  1. Google Cloud Platform
  2. Amazon Web Services
  3. Microsoft Azure
  4. Docker
  5. Oracle
  6. Terraform Cloud

# 操作方法


# 1. 安裝 Terraform

根據環境去選擇你的安裝方式

1
terraform version#檢查Terraform版本

# 2. 建置描述所需的雲端資源檔案 main.tf

Terrform 的資源描述檔案是使用.tf 的 HCL 檔案

範例 main.tf 建置 VM 在 GCP 上面並且建置好能啟動 Flask 的環境

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
# Create a single Compute Engine instance
resource "google_compute_instance" "default" {
name = "flask-vm"
machine_type = "f1-micro"
zone = "us-west1-a"
tags = ["ssh"]

boot_disk {
initialize_params {
image = "debian-cloud/debian-11"
}
}

# Install Flask
metadata_startup_script = "sudo apt-get update; sudo apt-get install -yq build-essential python3-pip rsync; pip install flask"

network_interface {
subnetwork = google_compute_subnetwork.default.id

access_config {
# Include this section to give the VM an external IP address
}
}
}
# 此為GCP官方網站的Example

# 3. 初始化 Terraform

在你的終端機輸入

1
terrform init

# 4. 檢驗 Terraform 的配置是否有錯誤

在你的終端機輸入

1
terraform plan

輸出畫面會告訴你新增 / 修改 / 刪除了哪些透過 Terraform 所建置的資源


# 5. 確認建置

在你的終端機輸入

1
terrform apply

# 完成了 你的雲端資源就架設完畢!!

真的蠻簡單蠻方便的
當然 Terraform 還有很多其他用法比如設定全域變數使用 variablle.tf 等等


# GitLab 範例在 GCP 建置 VM 透過 Terraform

Repository Link


# Terraform 挑戰與體驗

Qwiklabs 挑戰題目 都是非常簡單的題目

HTTPS Content-Based Load Balancer with Terraform

Modular Load Balancing with Terraform - Regional Load Balancer