Terraform 是 HashiCorp 的 Infrastructure as code 軟體,使用簡易範本化語言或 Json,提供簡單的方法來定義、預覽及部署雲端基礎結構。
下載
下載之後只是一個 Terraform 檔案,把他複製到 /usr/local/bin 底下,就可以直接使用
terraform
Terraform 格式,官方語法
vim aws.tf
---
# An AMI
variable "ami" {
description = "the AMI to use"
}
/* A multi
line comment. */
resource "aws_instance" "web" {
ami = "${var.ami}"
count = 2
source_dest_check = false
connection {
user = "root"
}
}
Json 格式
vim aws.tf.json
---
{
"variable": {
"ami": {
"description": "the AMI to use"
}
},
"resource": {
"aws_instance": {
"web": {
"ami": "${var.ami}",
"count": 2,
"source_dest_check": false,
"connection": {
"user": "root"
}
}
}
}
}
provider "google" {
credentials = "${file("account.json")}"
project = "my-project-id"
region = "us-central1"
}
resource "google_compute_instance" "vm_instance" {
name = "terraform-instance"
machine_type = "f1-micro"
boot_disk {
initialize_params {
image = "debian-cloud/debian-9"
}
}
network_interface {
# A default network is created for all GCP projects
network = "default"
access_config = {
}
}
}
下載 GCP Server 金鑰,之後重新命名為 account.json
vim terrafform.tf
---
provider "google" {
credentials = "${file("account.json")}"
project = "{{YOUR GCP PROJECT}}"
region = "us-central1"
zone = "us-central1-c"
}
resource "google_compute_instance" "vm_instance" {
name = "terraform-instance"
machine_type = "f1-micro"
boot_disk {
initialize_params {
image = "centos-cloud/centos-7"
}
}
network_interface {
# A default network is created for all GCP projects
network = "default"
access_config = {
}
}
}
terraform init
terraform apply
輸入:yes
resource "google_compute_instance" "default" {
...
metadata {
sshKeys = "pellok:${file("~/.ssh/id_rsa.pub")}"
}
}
terraform apply
terraform destroy
使用 Terraform 來操控 GCP,這樣就可以讓我們的雲端架構也可以程式化,讓架構可以自動化、標準化,減少人為的操控,讓主機的管理也有跡可循.在實作的過程中發現很多東西可以玩,之後可能會多加使用 Terraform 來管理主機.
Terraform,自动化配置与编排必备利器
Getting started with Terraform on Google Cloud Platform