Kanji
・클라우드 엔지니어 / 프리랜서 ・1993년생 ・에히메현 출신 / 도쿄도 시부야구 거주 ・AWS 경력 5년 프로필 상세
목차
사용자 정의 데이터 소스를 정의해야 하는 경우 외부 데이터 소스를 사용하십시오.
외부_외부 |데이터 소스 |해시코프/외부 |Terraform 레지스트리
기존 리소스에 대한 정보를 데이터 소스로 검색하려면 JSON 형식 문자열을 출력하는 스크립트(예: bash 또는 Python)를 사용합니다.
예를 들어 CodePipeline에는 호환되는 데이터 소스가 없으므로 쉘 스크립트를 사용하여 정보를 얻을 수 있습니다.
다음은 쉘 스크립트의 예입니다.
#!/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 스크립트를 참조합니다.
scripts
ListCodePipelineNames.sh
query 블록을 사용하면 codepipeline_name_prefix 를 인수로 지정할 수 있으므로 파이프라인 이름을 접두사로 필터링할 수 있습니다. codepipeline_name_prefix 를 지정하는 경우 지정된 문자열로 시작하는 파이프라인 이름만 참조하세요.
query
codepipeline_name_prefix
포인트는 아웃풋 부분이다.Terraform의 jsondecode() 함수를 사용하여 외부 데이터 소스 출력의 names 키에 있는 문자열을 다시 배열로 디코딩합니다.
jsondecode()
names
실제로 이 패턴을 사용하여 다른 리소스도 참조할 수 있습니다. 스크립트에서 배열을 문자열로 변환한 다음 추가 처리를 위해 Terraform에서 디코딩합니다.