基礎架構自動化編排工具-terraform

基礎架構自動化編排工具-terraform

Terraform 是什麼?

Terraform是用於安全高效地構建,更改和版本控制基礎結構的工具。Terraform可以管理現有和流行的服務提供商以及定製的內部解決方案。配置文件向Terraform描述了運行單個應用程序或整個數據中心所需的組件。Terraform生成執行計劃,以描述達到預期狀態所需執行的操作,然後執行該計劃以構建所描述的基礎結構。隨著配置的更改,Terraform能夠確定更改的內容並創建可以應用的增量執行計劃。Terraform可以管理的基礎結構包括底層組件(例如計算實例,存儲和網絡)以及高層組件(例如DNS條目,SaaS功能等)。官方說明

基礎架構自動化編排工具-terraform

為什麼需要它?

通常,我們在開發產品時,大量運用像是阿里雲、騰訊雲、AWS、GCP…等雲平臺,而隨著產品的增多,我們的機器規格可能會提升,或是架構需要調整,像新增 Cache 的機器…等,又或是我們有許多需求像是數據庫、負載均衡器…等諸多雲資源,這時Terraform 便是很好的工具去管理這些雲基礎架構。

經過 Terraform,我們不再需要手動到 Web 界面開啟一臺臺機器,不再需要手動配置 VPC,只需編寫好 Terraform 配置文件,一個鍵就能夠到達你想要做的事情,簡單來說就是你經過模板配置去管理這些雲資源,同時具有以下好處:

  • 能夠版本化去管理你的雲資源
  • 團隊成員都能夠經過 Terraform 配置理解目前所使用的雲資源和配置情況
  • 能夠自動化測試雲架構
  • 確保不同的環境 (eg Dev, Test, Prod) 都是相同的配置

Terraform 與其他的工具有什麼不同呢?

其他工具如 Chef, Ansible 他們最主要的功能是“配置管理”,即是要配置什麼環境變量…等之類的,而相較之下 Terraform 則是決定要什麼樣的機器。

跟 Terraform 最接近的工具則是 AWS 自行推出的 CloudFormation,但是固然 CloudFormation 也是經過文件去維護雲基礎架構,但是 Terraform 除了 AWS 能夠同時擴大到各家雲服務商,同時 Terraform 所制定的編寫方式相關於 CloudFormation 是十分的明晰易懂,容易上手維護,就我個人的經歷上也是較引薦使用 Terraform的。

下載安裝 Terraform(官方推薦)

www.terraform.io/downloads.html

安裝後直接在終端機執行 Terraform 指令

➜ ~ terraform -vTerraform v0.11.14
Your version of Terraform is out of date!
The latest versionis 0.12.12.
You can update by downloading from www.terraform.io/downloads.html
基礎架構自動化編排工具-terraform

如何編寫 Terraform 配置文件?

Terraform 的文件名是 *.tf,而根本的一個 Terraform 配置是經過叫做 HCL 言語撰寫,長得像是這樣

# Create a new instance of the latest Ubuntu 14.04 on an# t2.micro node with an AWS Tag naming it "HelloWorld"provider "aws" { region = "us-west-2"}
data "aws_ami" "ubuntu" {
most_recent = true
filter {
name = "name"
values = [
"ubuntu/images/hvm-ssd/ubuntu-trusty-14.04-amd64-server-*"
]
}

filter {
name = "virtualization-type"
values = ["hvm"]
}
owners = ["099720109477"] # Canonical

}
resource "aws_instance" "web" {
ami = "${data.aws_ami.ubuntu.id}"
instance_type = "t2.micro"
tags = { Name = "HelloWorld" }
}

上述表示是需求運用 AWS 的雲平臺,然後需求開啟一臺 EC2 Instance 的機器,其規格類型是 t2.micro 。

provider 是決定要對哪一個平臺操作, region 是 aws 需求的屬性。

而這裡這裡resource 的欄位意義是如下面的表示:

resource 雲資源名稱 自定義的名稱 {  

屬性 = 值
}

自定義的名稱能夠用來被其他資源引用。

除了這個最根本的定義資源語法之外,Terraform 還提供了像是:

Input Variables 讓你能夠像寫程式一樣運用變量,在反覆用到的地方,或是一些需求動態給予的值。

variable "image_id" { 
type = string
}
variable "availability_zone_names" {
type = list(string)
default = ["us-west-1a"]
}

你能夠經過 var.* 引用變量

resource "aws_instance" "this" { 
instance_type = "t2.micro"
ami = var.image_id
}

Output Values 輸出一些資源創立後你需要的值,最常見的像是 IP

output "instance_ip_addr" { 
value = aws_instance.this.private_ip
}

你經過 “<provider>__<name>_<attribute>” 去取值。/<attribute>/<name>/<provider>

Modules 當你有多個環境像是 Dev, Test, Prod,經過 Modules 能夠讓你不用在這些地方都寫一份相似的 Terraform,能夠集中寫一些 Modules 然後在用到的地方引入。

module "servers" { 
source = "./app-cluster"
servers =5
}

lifecycle 指定資源的生命週期,像是先創建新的,再移除舊的資源

resource "azurerm_resource_group" "this" { 
# ...
lifecycle {
create_before_destroy = true
}
}

如何執行 Terraform?

在運用 Terraform 前你需要先有云帳號,像是阿里雲、騰訊雲、 AWS 帳號、GCP 帳號,而以 AWS 為例,你需求先配置好 AWS 的 credentials。

再來你的目錄下,創建一個 main.tf 的文件,並編寫你的配置,然後下 terraform init 指令

➜ ~ terraform init
Initializing the backend...
Successfully configured the backend "s3"!
Terraform will automaticallyuse this backend unless the backend configuration changes.
Initializing provider plugins...
- Checking for available provider plugins on releases.hashicorp.com...
- Downloading plugin for provider "null" (2.1.2)...
- Downloading plugin for provider "aws" (2.33.0)...
- Downloading plugin for provider "template" (2.1.2)...
The following providers do not have any version constraints in configuration,so the latest version was installed.
To prevent automatic upgrades to new major versions that may contain breakingchanges,
It is recommended to add version = "..." constraints to thecorresponding provider blocks in configuration, with the constraint stringssuggested below.
* provider.aws: version = "~> 2.33"

* provider.null: version = "~> 2.1"
* provider.template: version = "~> 2.1"
Terraform has been successfully initialized!
You may now begin working with Terraform.
Try running "terraform plan" to seeany changes that are required for your infrastructure. All Terraform commandsshould now work.
If you ever set or change modules or backend configuration for Terraform,rerun this command to reinitialize your working directory. If you forget, othercommands will detect it and remind you to do so if necessary.

在這個指令中,Terraform 會去下載需要的插件,像是 AWS plugin。

接著經過 terraform plan 指令,能夠讓你在apply執行之前查看 Terraform 將做哪些哪些改動,這是為了避免我們修正到我們不應該修正的東西,或是有不是我們預期的結果

➜ ~ terraform plan
Refreshing Terraform state in-memory prior to plan…
The refreshed state will be used to calculate this plan, but will not bepersisted to local or remote state storage.
— — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — —
An execution plan has been generated and is shown below.
Resource actions are indicated with the following symbols:
+ create
Terraform will perform the following actions:
# aws_instance.this will be created
+ resource “aws_instance” “this” {
+ ami = “ami-212132212”
+ arn = (known after apply)
.....

你能夠看到上面 Terraform 通知我們有哪些東西會被改動,而當假如我們曾經有服務在上面時,也會通知我們有哪些會被刪除。這裡面的 known after apply 是表示在資源樹立後才會曉得的值。

接下來假如 plan 的改動都沒問題,就能夠執行 terraform apply 指令,去創建或改動雲資源

➜ ~ terraform apply
An execution plan has been generated and is shown below.
Resource actions are indicated with the following symbols:
+ create
....

最後,假如要刪除呢?你只需經過 terraform destroy 就能夠清理一切的資源了

➜ ~ terraform destroy
aws_instance.example:
Refreshing state
... [id=i-05f8863ba523a0082]
An execution plan has been generated and is shown below.
Resource actions are indicated with the following symbols:
- destroy
Terraform will perform the following actions:
# aws_instance.example will be destroyed
- resource "aws_instance" "this" {
...

其他常用的 Terraform CLI 指令

除了 init, plan, apply, destroy 之外

terraform fmt 由於多人編寫 Terraform 的 coding style 很大的可能會不同,該指令會統一轉成一定格式的內容。

terraform graph 讓你能夠用圖形看到一切資源的差異性。

terraform import 假如你曾經在雲上手動創建資源了,能夠經過該指令導入 Terraform 中

terraform validate 能否存在語法錯誤

Terraform Remote State

由於 Terraform 預設將一切創建的雲資源狀態存到terraform.tfstate文件,當有更改時會去這裡讀取狀態,但是當多人操作時,不同人電腦上的狀態是不同的,因而 Terraform 提供了 Remote State 的機制,讓 state 檔案統一放在一個地方。

Terraform 提供了以下能夠寄存的方式

  • AzureRM
  • Consul
  • GCS
  • Local
  • Manta
  • Postgres
  • Remote
  • S3

並提供了 terraform workspace 指令能夠切換不同的 state,由於像是 Dev 環境的 state 會跟 Prod 不一樣,應該要分開。

當然即便同一存在一箇中央,也可能發作 read write 牴觸的問題,所以 Terraform 預設會 lock 防止發作牴觸。

結論

到這裡我們簡單地介紹了 Terraform 的用處、如何編寫運用 Terraform,實際運用還有根據需求進行配置,但希望經過這樣的介紹可以讓你簡單快速的認識 Terraform。

有更多興趣推薦查看官方文檔

www.terraform.io/docs/configuration/index.html


分享到:


相關文章: