如何在 jmespath 中对字符串执行子字符串之类的函数

kos*_*oss 7 substring slice jmespath azure-cli2

  • 我想知道 JMESPATH 中是否有可以利用的子字符串函数(由 az cli 支持)。
  • 我有以下 az cli 请求,我只想提取具有安全组的链接子网的名称,但与其他云提供商不同,azure 不会以相同的方式存储关联的资源名称。

可以在subnet.id节点中提取名称, 如下所示

$ az network nsg show -g my_group -n My_NSG --query "subnets[].id" -o json
[
  "/subscriptions/xxxxxx2/resourceGroups/my_group/providers/Microsoft.Network/virtualNetworks/MY-VNET/subnets/My_SUBNET"
]
Run Code Online (Sandbox Code Playgroud)
  • 我只想 从结果中提取“MY_SUBNET” 。

我知道有一种叫做搜索的东西应该模仿子字符串(此处解释 https://github.com/jmespath/jmespath.jep/issues/5),但它对我不起作用。

$ az network nsg show -g my_group -n My_NSG  --query "subnets[].search(id,'@[120:-1]')" -o json
InvalidArgumentValueError: argument --query: invalid jmespath_type value: "subnets[].search(id,'@[120:-1]')"

CLIInternalError: The command failed with an unexpected error. Here is the traceback:
Unknown function: search()
Run Code Online (Sandbox Code Playgroud)

谢谢


编辑 :

我实际上运行的请求包括其他元素,这就是为什么在新行中使用带有 bash 的子字符串不是我想要的。这是完整查询的示例:

az network nsg show -g "$rg_name" -n "$sg_name" --query "{Name:name,Combo_rule_Ports:to_string(securityRules[?direction==\`Inbound\`].destinationPortRanges[]),single_rule_Ports:to_string(securityRules[?direction==\`Inbound\`].destinationPortRange),sub:subnets[].id,resourceGroup:resourceGroup}" -o json        
Run Code Online (Sandbox Code Playgroud)

输出

{
  "Combo_rule_Ports": "[]",
  "Name": "sg_Sub_demo_SSH",
  "resourceGroup": "brokedba",
  "single_rule_Ports": "[\"22\",\"80\",\"443\"]",
  "sub": [
    "/subscriptions/xxxxxxx/resourceGroups/brokedba/providers/Microsoft.Network/virtualNetworks/CLI-VNET/subnets/Sub_demo"
  ]
}
Run Code Online (Sandbox Code Playgroud)

Nan*_*ong 1

如果在 bash 中运行 Azure CLI,则可以执行以下字符串操作操作:

$substring以下语法从前面删除最长的匹配项$string

${string##substring}
Run Code Online (Sandbox Code Playgroud)

在这种情况下,您可以像这样检索子网。

var=$(az network nsg show -g nsg-rg -n nsg-name --query "subnets[].id"  -o tsv)
echo ${var##*/}
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

欲了解更多信息,您可以参考https://www.thegeekstuff.com/2010/07/bash-string-manipulation/