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 ) # Key point 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 中对其进行解码以进行进一步处理。