用 shell 解析 Json 的好工具 jq

JQ tutorial

Sample

$docker network inspect bridge

[{
  "Name": "bridge",
  "Id": ""fake-id",
  "Created": "2017-07-05T01:07:55.747497179Z",
  "Scope": "local",
  "Driver": "bridge",
  "EnableIPv6": false,
  "IPAM": {
    "Driver": "default",
    "Options": null,
    "Config": [{
      "Subnet": "172.17.0.0/16",
      "Gateway": "172.17.0.1"
    }]
  },
  "Internal": false,
  "Attachable": false,
  "Ingress": false,
  "ConfigFrom": {
    "Network": ""
  },
  "ConfigOnly": false,
  "Containers": {
    "b59a12af7c87621b43c95a9adbcf047076b8a4b6b6ce0d6c5e6e48e21188ce6a": {
    "Name": "heuristic_rosalind",
    "EndpointID": "fake-endpoint-id",
    "MacAddress": ""fake-mac-address",
    "IPv4Address": "172.17.0.2/16",
    "IPv6Address": ""
  }},
  "Options": {
  "com.docker.network.bridge.default_bridge": "true",
  "com.docker.network.bridge.enable_icc": "true",
  "com.docker.network.bridge.enable_ip_masquerade": "true",
  "com.docker.network.bridge.host_binding_ipv4": "0.0.0.0",
  "com.docker.network.bridge.name": "docker0",
  "com.docker.network.driver.mtu": "1500"
  },
  "Labels": {}
}]

寫個 shell 自動取得 IPv4Address

#!/bin/bash
#先拿到 `Containers` 底下的那串 hash
containers=`docker network inspect bridgejq .[0].Containersjq 'keys[]'`
echo "====== 取得 Container instance :${containers[0]}"
#取得 ipv4 Address
ipv4=`docker network inspect bridge"jq .[0].Containers.${containers}.IPv4Address`

這樣就很容易建立 bridge 讓 containers 互連啦 ~~

沒有留言:

張貼留言