Kanji
・雲端架構工程師 / 自由職業 ・1993年出生 ・愛媛縣出身 / 現居東京都澀谷區 ・5年 AWS 實戰經驗 個人檔案詳情
目錄
如果您需要定義自定義資料來源,請使用外部資料來源。
外部_外部|資料來源|Hashicorp/外部 |Terraform 登錄檔
要檢索有關作為資料來源的現有資源的資訊,請使用輸出 JSON 格式字串的指令碼(例如 bash 或 Python)。
例如,由於CodePipeline沒有相容的資料來源,您可以使用shell指令碼來獲取資訊。
這是一個 shell 指令碼示例:
#!/bin/bash eval "$(jq -r '@sh "codepipeline_name_prefix=\(.codepipeline_name_prefix)"')" pipelines=$(\ aws codepipeline \ list-pipelines \ --query "pipelines[?starts_with(name, '"${codepipeline_name_prefix}"')].name" \ --region ap-northeast-1 \ --output json ) # 如何在Terraforms資料來源中獲取多個AWS資源的資訊 result=$(cat << EOS { "names": $(echo "${pipelines}" | jq '@json') } EOS ) jq -n "$result"
#關鍵點
|jq '@json'
# Before the change result=$(cat << EOS { "names": $(echo "${pipelines}") } EOS ) # Resulting variable { "names": [ "test-pipeline01", "test-pipeline02", "test-pipeline03", "test-pipeline04", "test-pipeline05" ] }
% terraform plan data.external.aws_codepipelines: Reading... ╷ │ Error: Unexpected External Program Results │ │ with data.external.aws_codepipelines, │ on test.tf line 2, in data "external" "aws_codepipelines": │ 2: program = ["bash", "${path.module}/ListCodePipelineNames.sh"] │ │ The data source received unexpected results after executing the program. │ │ Program output must be a JSON encoded map of string keys and string values. │ │ If the error is unclear, the output can be viewed by enabling Terraform's logging at TRACE level. │ Terraform documentation on logging: https://www.terraform.io/internals/debugging │ │ Program: /bin/bash │ Result Error: json: cannot unmarshal array into Go value of type string
|將陣列轉換為字串jq '@json'
# After the change result=$(cat << EOS { "names": $(echo "${pipelines}" | jq '@json') } EOS ) # Resulting variable { "names": "[\"test-pipeline01\",\"test-pipeline02\",\"test-pipeline03\",\"test-pipeline04\",\"test-pipeline05\"]" }
data "external" "aws_codepipelines" { program = ["bash", "${path.module}/scripts/ListCodePipelineNames.sh"] query = { codepipeline_name_prefix = "test-pipeline0" } } # Key point output "aws_codepipelines_names" { value = jsondecode(data.external.aws_codepipelines.result["names"]) }
在與 Terraform 模板相同的目錄中建立一個“scripts”目錄,並引用“ListCodePipelineNames.sh”指令碼。
“query”塊允許您指定“codepipeline_name_prefix”作為引數,因此您可以按字首過濾管道名稱。 如果指定“codepipeline_name_prefix”,則僅引用以指定字串開頭的管道名稱。
關鍵點是輸出部分。使用 Terraform 的“jsondecode()”函式將“names”鍵中的字串從外部資料來源輸出解碼回陣列。
實際上,您也可以使用此模式來引用其他資源:在指令碼中將陣列轉換為字串,然後在 Terraform 中對其進行解碼以進行進一步處理。