

本文為英文版的機器翻譯版本，如內容有任何歧義或不一致之處，概以英文版為準。

# 了解 Terraform 變數、本機值和輸出
<a name="variables-locals-outputs"></a>

變數透過允許程式碼區塊內的預留位置來增強程式碼彈性。每次重複使用程式碼時，變數可以代表不同的值。Terraform 會依其模組化範圍區分其變數類型。輸入變數是可插入模組的外部值，輸出值是可在外部共用的內部值，而本機值一律保持在其原始範圍內。

## Variables
<a name="variables"></a>

AWS CloudFormation 使用 [參數](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/parameters-section-structure.html)來表示可以從一個堆疊部署設定和重設到下一個堆疊的自訂值。同樣地，Terraform 會使用[輸入變數](https://developer.hashicorp.com/terraform/language/values/variables)或*變數*。變數可以在 Terraform 組態檔案中的任何位置宣告，通常使用所需的資料類型或預設值宣告。以下三個表達式都是有效的 Terraform 變數宣告。

```
variable "thing_i_made_up" {
  type = string
}

variable "random_number" {
  default = 5
}

variable "dogs" {
  type = list(object({
    name  = string
    breed = string
  }))

  default = [
    {
      name  = "Sparky",
      breed = "poodle"
    }
  ]
}
```

若要在組態中存取 Sparky 的品種，您可以使用變數 `var.dogs[0].breed`。如果變數沒有預設值，且未分類為 null 值，則必須為每個部署設定變數的值。否則，您可以選擇是否要為變數設定新值。在根模組中，您可以在[命令列](https://developer.hashicorp.com/terraform/language/values/variables#variables-on-the-command-line)、[環境](https://developer.hashicorp.com/terraform/language/values/variables#environment-variables)變數或 [terraform.tfvars](https://developer.hashicorp.com/terraform/language/values/variables#variable-definitions-tfvars-files) 檔案中設定目前的變數值。下列範例顯示如何在 **terraform.tfvars** 檔案中輸入變數值，該檔案存放在模組的頂層目錄中。

```
# terraform.tfvars
dogs = [
   { 
      name  = "Sparky", 
      breed = "poodle" 
   },
   { 
      name  = "Fluffy", 
      breed = "chihuahua" 
   }
]

random_number = 7

thing_i_made_up = "Kabibble"
```

此範例 **terraform.tfvars** 檔案`dogs`中的 值會覆寫變數宣告中的預設值。如果您要在子模組中宣告變數，您可以直接在模組宣告區塊內設定變數值，如下列範例所示。

```
module "my_custom_module" {
  source        = "modulesource/custom"
  version       = "0.0.1"
  random_number = 8
}
```

宣告變數時，您可以使用的一些其他引數包括：
+ `sensitive` – 將此設定為`true`防止變數值在 Terraform 程序輸出中公開。 
+ `nullable` – 將此設定為`true`允許變數沒有值。對於未設定預設值的變數來說，這很方便。
+ `description` – 將變數的描述新增至堆疊的中繼資料。
+ `validation` – 設定變數的驗證規則。

Terraform 變數最方便的層面之一是能夠在變數宣告中新增一或多個驗證物件 。您可以使用驗證物件來新增變數必須通過的條件，否則部署會失敗。您也可以設定自訂錯誤訊息，以便在違反條件時顯示。

例如，您正在設定團隊成員將執行的 Terraform 組態檔案。部署堆疊之前，團隊成員需要建立 **terraform.tfvars** 檔案來設定重要的組態值。若要提醒他們，您可以執行類似下列的動作。

```
variable "important_config_setting" {
  type = string

  validation {
    condition     = length(var.important_config_setting) > 0
    error_message = "Don't forget to create the terraform.tfvars file!"
  }

  validation {
    condition     = substr(var.important_config_setting, 0, 7) == "prefix-"
    error_message = "Remember that the value always needs to start with 'prefix-'"
  }
}
```

如本範例所示，您可以在單一變數內設定多個條件。Terraform 只會顯示失敗條件的錯誤訊息。如此一來，您就可以對變數值強制執行所有類型的規則。如果變數值導致管道故障，您會確切知道原因。

## 本機值
<a name="local-values"></a>

如果模組中有任何您想要別名的值，請使用 `locals`關鍵字，而不是宣告永遠不會更新的預設變數。顧名思義，`locals`區塊包含內部範圍限定於該特定模組的術語。如果您想要轉換字串值，例如將字首新增至變數值以用於資源名稱，則使用本機值可能是很好的解決方案。單一`locals`區塊可以宣告模組的所有本機值，如下列範例所示。

```
locals {
  moduleName    = "My Module"
  localConfigId = concat("prefix-", var.important_config_setting)
}
```

請記住，當您存取 值時，`locals`關鍵字會變成單一，例如 `local.LocalConfigId`。

## 輸出值
<a name="output-values"></a>

如果 Terraform 輸入變數類似 CloudFormation 參數，您可以說 [Terraform 輸出值](https://developer.hashicorp.com/terraform/language/values/outputs)類似 [CloudFormation 輸出](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/outputs-section-structure.html)。兩者都用於公開部署堆疊內的值。不過，由於 Terraform 模組更深入工具的結構，因此 Terraform 輸出值也會用來將模組內的值公開給父模組或其他子模組，即使這些模組都位於相同的部署堆疊中。如果您要建置兩個自訂模組，而第一個模組需要存取第二個模組的 ID 值，則需要將下列`output`區塊新增至第二個模組。

```
output "module_id" {
  value = local.module_id
}
Then in the first module you could use it like this:
module "first_module" {
  source = "path/to/first/module"
}

resource "example_resource" "example_resource_name" {
  module_id = module.first_module.module_id
}
```

由於 Terraform 輸出值可在相同堆疊內使用，因此您也可以在 `output` 區塊中使用 `sensitive` 屬性來禁止該值顯示在堆疊輸出中。此外，`output`區塊可以使用`precondition`與變數使用區塊相同的`validation`區塊： 以確保變數遵循特定的規則集。這有助於確保模組中的所有值都如預期存在，然後再繼續部署。

```
output "important_config_setting" {
  value = var.important_config_setting

  precondition {
    condition     = length(var.important_config_setting) > 0
    error_message = "You forgot to create the terraform.tfvars file again."
  }
}
```