gpt4 book ai didi

amazon-web-services - AWS cli JMESpath 查询标签值

转载 作者:行者123 更新时间:2023-12-04 08:04:56 25 4
gpt4 key购买 nike

作为我的 previous question 的后续行动,我无法让标签在这种类型的输出中正常工作。我想打印一个表格,其中每个属性都是一行。这是我期望的样子:

% aws --output table ec2 describe-instances --instance-id $id --query "Reservations[].Instances[0].[{ Property: 'Type', Value: InstanceType }]"         
-------------------------------
| DescribeInstances |
+-----------+-----------------+
| Property | Value |
+-----------+-----------------+
| Type | g4dn.12xlarge |
+-----------+-----------------+

但是标签名称看起来像这样:

% aws --output table ec2 describe-instances --instance-id $id --query "Reservations[].Instances[0].[{ Property: 'Name', Value: Tags[?Key =='Name'].Value }]"   
-------------------
|DescribeInstances|
+-----------------+
| Property |
+-----------------+
| Name |
+-----------------+
|| Value ||
|+---------------+|
|| Elliott-TKD ||
|+---------------+|

标签值是正确的,但格式很奇怪,当与更多其他行组合时,表格会变得非常难看。

最佳答案

查询的过滤器部分 ( [?Key == 'Name'] ) 正在创建 JMESPath 描述为 projection 的内容.
您必须重置此投影才能从中提取单个字符串。
可以使用 pipes 来重置投影.

Projections are an important concept in JMESPath. However, there are times when projection semantics are not what you want. A common scenario is when you want to operate of the result of a projection rather than projecting an expression onto each element in the array.For example, the expression people[*].first will give you an array containing the first names of everyone in the people array. What if you wanted the first element in that list? If you tried people[*].first[0] that you just evaluate first[0] for each element in the people array, and because indexing is not defined for strings, the final result would be an empty array, []. To accomplish the desired result, you can use a pipe expression, <expression> | <expression>, to indicate that a projection must stop.

来源:https://jmespath.org/tutorial.html#pipe-expressions

因此您的问题非常接近他们在文档中描述的内容,并且可以使用以下方法重置该投影:

Tags[?Key =='Name']|[0].Value 

或者,用:

Tags[?Key =='Name'].Value | [0]

这是两个完全相同的查询。

给定 JSON:

{
"Reservations": [
{
"Instances": [
{

"Tags": [
{
"Key": "Name",
"Value": "Elliott-TKD"
},
{
"Key": "Foo",
"Value": "Bar"
}
]
}
]
}
]
}

查询

Reservations[].Instances[0].[{ Property: `Name`, Value: Tags[?Key == `Name`]|[0].Value }]

会给出预期

[
[
{
"Property": "Name",
"Value": "Elliott-TKD"
}
]
]

所以它会在您的表格中正确呈现

------------------------------
| DescribeInstance |
+------------+---------------+
| Property | Value |
+------------+---------------+
| Name | Elliott-TKD |
+------------+---------------+

关于amazon-web-services - AWS cli JMESpath 查询标签值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66265091/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com