Spa*_*nky 8 awk google-compute-engine gcloud
我有一堆在GCE中运行的实例.我想以编程方式获取它们的内部IP地址列表,而无需登录实例(本地).
我知道我可以跑:
gcloud compute instances list
Run Code Online (Sandbox Code Playgroud)
但是有没有我可以通过的标志来获取我想要的信息?例如
gcloud compute instances list --internal-ips
Run Code Online (Sandbox Code Playgroud)
或者类似的?或者我将不得不掸掉我的sed/awk大脑并解析输出?
我也知道我可以使用--format = json在JSON中获取输出,但我正在尝试在bash脚本中执行此操作.
acu*_*ich 29
以编程方式获取内部IP(或外部IP)列表而不依赖于除以下任何工具之外的最简单方法gcloud
:
$ gcloud --format="value(networkInterfaces[0].networkIP)" compute instances list
$ gcloud --format="value(networkInterfaces[0].accessConfigs[0].natIP)" compute instances list
Run Code Online (Sandbox Code Playgroud)
这种使用--format=value
还需要投影,该投影是选择资源数据值的资源键列表.对于任何可用于--format=flattened
获取资源键/值对列表的命令:
$ gcloud --format=flattened compute instances list
Run Code Online (Sandbox Code Playgroud)
这里有一些事情.
第一个gcloud的列表默认输出格式不保证稳定,将来可能会添加新列.不要反对这个脚本!
三种输出模式是可通过格式标志访问的三种输出模式, - format = json, - format = yaml和format = text,基于键=值对,即使引入了新字段也可以编写脚本在将来.
做你想做的事的两个好方法是使用JSON和jq工具,
gcloud compute instances list --format=json \
| jq '.[].networkInterfaces[].networkIP'
Run Code Online (Sandbox Code Playgroud)
或文本格式和grep +面向行的工具,
gcloud compute instances list --format=text \
| grep '^networkInterfaces\[[0-9]\+\]\.networkIP:' | sed 's/^.* //g'
Run Code Online (Sandbox Code Playgroud)
据我所知,您无法在 gcloud 工具中过滤特定字段。像这样的东西适用于 Bash 脚本,但它仍然感觉有点脆弱:
gcloud compute instances list --format=yaml | grep " networkIP:" | cut -c 14-100
Run Code Online (Sandbox Code Playgroud)