2017-09-12 1 views
0

나는 UUID (terraform.tfstate 파일)를 사용하여 서로를 참조하는 다양한 유형의 객체 배열을 가지고 있습니다. 두 객체가 해당 UUID 중 하나와 관련이있는 다른 객체의 다른 값의 모양을 기반으로 한 객체에서 하나의 값을 선택하고 싶습니다.jq : 다른 배열 요소의 값으로 검색

예를 들면, 나는이 작업을 수행 할 수 있습니다

$ jq '.modules[].resources[] 
| select(.type == "openstack_compute_instance_v2" and 
     .primary.attributes.name == "jumpbox").primary.id' terraform.tfstate 
"5edfe2bf-94df-49d5-8118-3e91fb52946b" 
$ jq '.modules[].resources[] 
| select(.type =="openstack_compute_floatingip_associate_v2" and 
     .primary.attributes.instance_id == "5edfe2bf-94df-49d5-8118-3e91fb52946b").primary.attributes.floating_ip' terraform.tfstate 
"10.120.241.21" 

를 이름에 따라 나에게 'jumpbox'VM의 외부 유동 IP를 부여.

나는 모두 하나의 jq 전화를하고 싶습니다. 그게 가능하니?

답변

0

당신은 우리가 당신이

{ 
    "modules": [ 
    { 
     "resources": [ 
     { 
      "type": "openstack_compute_instance_v2", 
      "primary": { 
      "id": "5edfe2bf-94df-49d5-8118-3e91fb52946b", 
      "attributes": { 
       "name": "jumpbox" 
      } 
      } 
     }, 
     { 
      "type": "openstack_compute_floatingip_associate_v2", 
      "primary": { 
      "attributes": { 
       "instance_id": "5edfe2bf-94df-49d5-8118-3e91fb52946b", 
       "floating_ip": "10.120.241.21" 
      } 
      } 
     } 
     ] 
    } 
    ] 
} 
과 같은 데이터를 추론 할 수

$ jq ' 
     .modules[].resources[] 
    | select(.type == "openstack_compute_instance_v2" and .primary.attributes.name == "jumpbox") 
    | .primary.id 
' terraform.tfstate 
"5edfe2bf-94df-49d5-8118-3e91fb52946b" 

$ jq ' 
     .modules[].resources[] 
    | select(.type =="openstack_compute_floatingip_associate_v2" and .primary.attributes.instance_id == "5edfe2bf-94df-49d5-8118-3e91fb52946b") 
    | .primary.attributes.floating_ip 
' terraform.tfstate 
"10.120.241.21" 

(일부 재 포맷을 갖는)을 명령에서 뒤쪽으로 작업을 더 샘플 데이터 만 를 제공하는 경우가 대답하기 쉬울 것

다음 필터는 functions, variablesparenthesis()을 사용하는 솔루션을 보여줍니다.

이 필터는 filter.jq에 있으며 data.json 다음

$ jq -M -f filter.jq data.json 

을 위의 샘플 데이터를 포함하는 경우

def get_primary_id($name): 
    select(.type == "openstack_compute_instance_v2" 
     and .primary.attributes.name == $name) 
    | .primary.id 
; 
def get_floating_ip($id): 
    select(.type =="openstack_compute_floatingip_associate_v2" 
     and .primary.attributes.instance_id == $id) 
    | .primary.attributes.floating_ip 
; 
    .modules[] 
| (.resources[] | get_primary_id("jumpbox")) as $id 
| (.resources[] | get_floating_ip($id)  ) as $fip 
| ($id, $fip) 

는 출력을 생성합니다

"5edfe2bf-94df-49d5-8118-3e91fb52946b" 
"10.120.241.21" 
+0

너무 감사합니다! 그것은 많은 의미가 있습니다. – dhaines

관련 문제