iT邦幫忙

2021 iThome 鐵人賽

DAY 27
0

Terraform 前言

今天介紹一下可以快速建立GCP各服務的套件Terraform,那麼Terraform是什麼?

  • 一句話說明的話可以這麼說,一個可支援多雲端平台部署工具。
  • 可以根據Terraform建立的樣板(.tf欓)透過指令快速建立起雲端所需的服務,也可以建立起資料夾結構一次性的建立多種類雲端服務(比方說VM 防火牆規則 硬碟等等...)

安裝Terraform (MAC)

brew tap hashicorp/tap
brew install hashicorp/tap/terraform

terraform -version

開始Terraform (GCP)

  1. 建立起對應之料夾
  2. 建立起安裝檔案樣板欓(main.tf)
  3. 取得GCP credentials json key
  4. 設定main.tf參數
mkdir test-terraform
cd test-terraform
touch main.tf

Terraform參數 (GCP VM)

  • 舉例來說建立一台VM掛載外部硬碟

    • 設定專案
    provider "google" {
    credentials = file("/Dev/terraform/project-xxxxxx.json")
    project     = "project"
    region      = "asia-east1"
    }
    
    • 設定外部硬碟
    resource "google_compute_disk" "disk" {
    name  = "test-disk"
    type  = "pd-standard"
    zone  = "asia-east1-a"
    size  = 50
    }
    
    • 設定VM規格
    產生VM name亂數
    
    resource "random_id" "instance_id" {
    byte_length = 8
    }
    
    設定VM規格
    
    resource "google_compute_instance" "test-vm" {
    name         = "test-vm-${random_id.instance_id.hex}"
    machine_type = "n1-standard-4"
    zone         = "asia-east1-a"
    
    VM作業系統
    
    boot_disk {
     initialize_params {
       image = "centos-cloud/centos-7"
     }
    }
    
    • 設定網路
    network_interface {
     network = "default"
     subnetwork = "xxxxxx"
    
     access_config {
     }
    }
    
    • 開機設定
    metadata_startup_script = "mkfs.ext4 -m 0 -F -E lazy_itable_init=0,lazy_journal_init=0,discard /dev/sdb; mkdir -p /mnt/disk/test; mount -o discard,defaults /dev/sdb /mnt/disk/test; chmod a+w /mnt/disk/test; echo UUID=`blkid -s UUID -o value /dev/sdb` /mnt/disk/test ext4 discard,defaults,nofail 0 2 >> /etc/fstab "
    
    
    • 綁定Disk VM
    resource "google_compute_attached_disk" "default" {
    disk     = google_compute_disk.disk.id
    instance = google_compute_instance.test-vm.id
    }
    

Terraform運作 (GCP)

  1. 初始化檔案
  2. 驗證參數正確性
  3. 驗證執行正確性
  4. 建立服務
  5. 刪除服務
terraform init 

output:
Terraform has been successfully initialized!

terraform validate 

output:
Success! The configuration is valid.

terraform plan

output:
Plan: 4 to add, 0 to change, 0 to destroy.

terraform apply

output: 輸入 yes
Enter a value: yes
Apply complete! Resources: 4 added, 0 changed, 0 destroyed.

terraform destroy

output: 輸入 yes
Plan: 0 to add, 0 to change, 4 to destroy.

Do you really want to destroy all resources?
  Terraform will destroy all your managed infrastructure, as shown above.
  There is no undo. Only 'yes' will be accepted to confirm.

  Enter a value: yes

上一篇
Cloud Monitor
下一篇
GCP GAE
系列文
GCP的雲端世界30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言