Site icon Mr. 沙先生

Terraform Enterprise 把 state pull 到 local 跑 plan 測試

這篇是菜菜的筆記,怕下次跑的時候忘記,記錄一下 …

 

最近剛接手要準備大量管理 AWS Account 所以準備開始玩 TFE (Terraform Enterprise),,TFE 有別於不同 CloudFormation 是 state 要自己管理,而 TFE 可以幫忙管理 state,如果沒有 TFE 則要自幹放在 S3 或者其他的 backend。

 

在測試 Terraform code 的時候在 Local 端通常都還是需要 plan 一下看是否有寫錯格式或衝突之類的,但由於管理委託給 TFE,所以要在 Local plan 的話要 pull 下來。

 

簡單記錄一下怎麼把 TFE 上面的 state pull 到 local 端 …

 

先假設已經有在 TFE 上開 Workspace 環境 (organization/),然後你的 main.tf 要填上 state backend 的資訊

例如:

# main.tf

terraform {
  backend "atlas" {
    name = "104corp/foobar-prod"
  }
}

 

Note !! atlas 是 HashiCorp 舊的 Enterprise 產品 (2018 年下線),但 TFE backend 這邊還沒改正,所以要用 TFE backend 要先寫 atlas … 如果 TFE 改好了這邊文章還沒修正的話記得提醒我一下 …

 

然後到 User Token 這邊產生用於 TFE 的 Token

 

回到 Local 把 Key 塞到環境變數,或者直接塞去 bashrc

$ export ATLAS_TOKEN=xabAnD4jI...

 

執行 state pull 就可以拿到現在當前的 state

$ terraform state pull

 

要拿來 plan 用的話可以 output 到 terraform.tfstate

$ terraform state pull > terraform state pull > terraform.tfstate

 

如果 state 有更新記得 local 的也要更新,不過我通常會寫成 Makefile

# Makefile
.PHONY: default

#
default: help

help:
  @echo 'Use "make" <plan, pull> to run terraform.'

plan:
  test -e terraform.tfstate || terraform state pull > terraform.tfstate
  @echo ">>> terraform plan ..."
  terraform plan
  @echo ">>> clean state ..."
  test -e terraform.tfstate && rm terraform.tfstate

pull:
  @echo ">>> terraform state pull ..."
  terraform state pull > terraform.tfstate

 

大致上就是這樣了。

 

Exit mobile version