我正在嘗試將串列的內容復制到 terraform 中的檔案中。這是我的 variables.tf 檔案。
variable "fruits" {
type = list
description = "List Of Fruits"
default = [ "Apple" , "Banana" , "Mango" ]
}
variable "animals" {
type = map
description = "Map of animals"
default = {
herbivores = "sheep"
carnovore = "lion"
omnivore = "bear"
}
}
variable "birds" {
type = string
description = "A string for Bird"
default = "parrot"
}
variable "bool" {
default = "true"
}
variable "filenames" {
default = "Terraform_Basics.txt"
}
我正在嘗試創建一個資源型別 local_file ,它將包含地圖和串列值的內容。能夠復制單個值,但不能一次捕獲所有值以復制到檔案中。
resource "local_file" "pet" {
filename = var.filenames
content = var.fruits[0]
}
我是 terraform 的新手,有人可以幫助我如何實作這一目標。
uj5u.com熱心網友回復:
為此,需要進行一項非常重要的更改。即使您設法讓它適用于所有元素,您也會收到以下錯誤:
var.fruits is a list of dynamic, known only after apply
var.pets is a map of dynamic, known only after apply
對于這些型別的測驗,我通常建議使用local變數 [1]。它們的值不是動態的并且是已知的。所以對于第一部分,我會將變數定義更改為區域變數:
locals {
fruits = ["Apple", "Banana", "Mango"]
pets = {
herbivores = "sheep"
carnovore = "lion"
omnivore = "bear"
}
filenames = "Terraform_Basics.txt"
}
現在,要注意的另一件事是,您在示例中為您提供了一個邏輯名稱的檔案,pets同時您試圖輸出水果的值,這可能會導致很多混亂。以下是您的resource塊的外觀:
resource "local_file" "fruits" {
...
}
resource "local_file" "pets" {
...
}
我將解釋需要添加到資源塊中的內容。您想要獲取地圖/串列的所有元素。為此,您可以使用splat運算式 [2]。如果它是一個串列,那么您可以簡單地執行以下操作:
resource "local_file" "fruits" {
filename = local.filenames
content = join(", ", local.fruits[*])
}
對于地圖,語法略有不同,因為您將使用values同樣回傳串列的內置函式 [3],因此在這種情況下也需要 splat 運算式:
resource "local_file" "pets" {
filename = local.filenames
content = join(", ", values(local.pets)[*])
}
請注意,您需要使用一個額外的內置函式,即join[4]。如果您嘗試僅在 中傳遞區域變數值content,您將收到以下錯誤:
Inappropriate value for attribute "content": string required.
如果您希望進一步改進代碼,我的建議是為寵物和水果創建一個不同的檔案名,否則它將不斷被覆寫:
locals {
fruits = ["Apple", "Banana", "Mango"]
pets = {
herbivores = "sheep"
carnovore = "lion"
omnivore = "bear"
}
filename_pets = "Terraform_Basics_Pets.txt"
filename_fruits = "Terraform_Basics_Fruits.txt"
}
然后,在資源塊中:
resource "local_file" "fruits" {
filename = local.filename_fruits
content = join(", ", local.fruits[*])
}
resource "local_file" "pets" {
filename = local.filename_pets
content = join(", ", values(local.pets)[*])
}
[1] https://www.terraform.io/language/values/locals
[2] https://www.terraform.io/language/expressions/splat
[3] https://www.terraform.io/language/functions/values
[4] https://www.terraform.io/language/functions/join
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/495786.html
下一篇:根據另一個串列回傳連續出現的串列
