本文介绍了如何从ec2 describe-instances中提取特定的键值标签的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我从describe-instances中获得了以下内容:

I've got the following from describe-instances:

{
    "Reservations": [
        {
            "Instances": [
                {
                    "PublicDnsName": "ec2-xxxxx.amazonaws.com",
                    "Tags": [
                        {
                            "Key": "Name",
                            "Value": "yyyyy"
                        },
                        {
                            "Key": "budget_cluster",
                            "Value": "zzzzz"
                        },
                        {
                            "Key": "poc",
                            "Value": "aaaaaaa"
                        }
                    ]
                }
            ]
        }
    ]
}

对于每个实例,我想提取PublicDnsName和"budget_cluster"标记键的值.如何使用ec2 describe-instancesjq做到这一点?

For each instance, I would like to extract the PublicDnsName and the value of the "budget_cluster" tag key. How to do this either with ec2 describe-instances or with jq ?

推荐答案

修改弗雷德里克的答案:

Modifying Frédéric's answer:

aws ec2 describe-instances --output text --query \
   'Reservations[].Instances[].[PublicDnsName, Tags[?Key==`budget_cluster`].Value | [0]]'

会产生:

ec2-xxxxx.amazonaws.com zzzzz
ec2-bbbbb.amazonaws.com yyyyy

我将输出更改为文本,这会删除尽可能多的格式,并使用| [0]选择单个标签值,因为无论如何每个实例都只有一个.最后,我在最后删除了[],以使结果列表不会变平.这样,在文本输出中,每个条目将在其单独的行上.

I've changed the output to text, which removes as much formatting as possible and selected the individual tag value with | [0] since there will only ever be one per instance anyway. Finally, I removed the [] at the end so that the resulting list isn't flattened. That way in text output each entry will be on its own line.

您还可以通过仅选择实际具有该标签的实例来使其更加健壮.您可以通过对--query参数进行进一步修改来执行此操作,但是在这种情况下,最好使用--filters参数,因为它会进行服务端过滤.具体来说,您需要tag-key过滤器:--filters "Name=tag-key,Values=budget_cluster"

You can also make this more robust by only selecting instances that actually have that tag. You could do so with further modifications to the --query parameter, but it is better in this case to use the --filters parameter since it does service-side filtering. Specifically you want the tag-key filter: --filters "Name=tag-key,Values=budget_cluster"

aws ec2 describe-instances --output text \
    --filters "Name=tag-key,Values=budget_cluster" --query \
   'Reservations[].Instances[?Tags[?Key==`budget_cluster`]].[PublicDnsName, Tags[?Key==`budget_cluster`].Value | [0]]'

仍然会产生:

ec2-xxxxx.amazonaws.com zzzzz
ec2-bbbbb.amazonaws.com yyyyy

但是通过有线方式,您只会得到您关心的实例,从而节省了带宽费用.

But over the wire you would only be getting the instances you care about, thus saving money on bandwidth.

这篇关于如何从ec2 describe-instances中提取特定的键值标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-19 21:43