今天介紹一下可以快速建立GCP各服務的套件Terraform,那麼Terraform是什麼?
brew tap hashicorp/tap
brew install hashicorp/tap/terraform
terraform -version
mkdir test-terraform
cd test-terraform
touch main.tf
舉例來說建立一台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 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 "
resource "google_compute_attached_disk" "default" {
disk = google_compute_disk.disk.id
instance = google_compute_instance.test-vm.id
}
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