昨天的文章中有提到,在我的觀點裡,Terraform 有三個最重要的概念:Provider、State 和 Modules
refresh
來刷新真實 infra 的狀態。因此當我們改變 config 時,Terraform 會發現 state 與 config 不符(state difference),我們可以採用 terraform apply
來把這些現實 infra 改成像 config 所描述的一樣。terraform.tfstate
檔案中,不過為了滿足團隊協作的可能性,可以選擇將 state file 存放在雲端。Terraform 會根據 backend
設定的內容,決定這些 state file 要放置在哪裡。假設一個大兩採用 AWS resource 的情境下,則可以選擇將 state file 放在 S3 bucket 中,而我們只需要把 backend
設定為 S3 即可。terraform apply
的資料夾層級就是 root module以上是一些關於 Terraform 運作的基本介紹。因此,一個簡單的 Terraform module 的範例可能會有以下的 file tree:
.
├── **example-module/**
│ ├── subnet-private.tf
│ ├── subnet-public.tf
│ └── vpc.tf
├── ec2.tf
└── main.tf
其中的 example-module/
即為上面提到的 child module,而外層 main.tf
裡面會包含 provider 與 backend 的設定:
terraform {
required_version = "~> 1.7"
required_providers {
aws = {
source = "hashicorp/aws"
version = "~> 5.21"
}
}
backend "s3" {
bucket = "example-tfstates"
key = "path/to/repo.tfstate"
region = "ap-northeast-1"
dynamodb_table = "tf-locks"
profile = "tf-example-profile"
}
}
provider "aws" {
region = "ap-northeast-1"
profile = "tf-example-profile"
default_tags {
tags = {
Managed = "terraform"
Source = "path/to/repo"
}
}
}
在有了對 Terraform 的基本認識之後,接著可以來看看實際上使用 Terraform 幫我們管理 infra 的流程
設定、固定 terraform 版本
通常會利用 tfenv
這個工具來當作 Terraform 版本的管理工具,以下是常見的指令:
tfenv list
查看本地現有版本tfenv list-remote
查看所有現有版本tfenv install x.x.x
安裝tfenv use x.x.x
使用tfenv pin
將當前 folder 固定為當前版本建立檔案 main.tf
,設定 provider & backend
Provider & profile:Terraform 可以透過 AWS 的 credential_process
執行 function,function 內可以執行取回某個 profile 的 SessionToken,讓 Terraform 可以透過這個 profile 存取資源
📎 需要額外使用
credential_process
創造tf-[profile]
的新 profile 原因
- 公司現有的 roles 預設都需要 MFA 才能使用,但 terraform 沒辦法跳 prompt 輸入 MFA
- 不使用
credential_process
都會採用跟aws-vault
一樣的背景執行 profile因此,在本地的 aws-config 檔案裡,除了上面的
main.tf
範例中的tf-example-profile
,也存在另一個 profileexample-profile
用來做 command line 的 assume role 用(細節可以參考 aws-vault 的用法,因為篇幅有限這邊暫不討論)
Backend 設定
key
:S3 bucket 中 state file 的路徑,主要用來區分專案或者 module下指令 terraform init
:初始化整個 Terraform module。這個指令會把 module 中用到的 published module,以及 child modules 複製到當前目錄的 .terraform/
中,並且初始化存放 state 的 backend,讓一切的設定可以開始運作
介紹完管理 infra 的基本概念與工具後,下一篇會先簡介該怎麼透過 Terraform 管理 EKS、以及使用 EKS 時需要用到的相關 AWS 資源,緊接著就會開始介紹 K8s 的基本概念。
現在才有種正式進入正題的感覺!