简体   繁体   中英

How to filter results from AWS CLI command

How can I filter the following so just results with IP starting with 10.* are returned?

aws ec2 describe-instances --filters "Name=tag-value,Values=mytagavalue" --query 'Reservations[*].Instances[*].{InstanceId:InstanceId,PrivateDnsName:PrivateDnsName,State:State.Name, IP:NetworkInterfaces[0].PrivateIpAddress}'
[
    [
        {
            "InstanceId": "i-12345bnmsdfod",
            "PrivateDnsName": "ip-10-34-24-4.my.there.com",
            "State": "running",
            "IP": "10.10.10.4"
        }
    ],
    [
        {
            "InstanceId": "i-12345bnmsdfop",
            "PrivateDnsName": "",
            "State": "terminated",
            "IP": null
        }
    ],

Option 1) Via Filters

Use the network-interface.addresses.private-ip-address filter to select values matching only "10.*", which will match addresses starting with "10.".

--filters "Name=network-interface.addresses.private-ip-address,Values=10.*"

Simply include a space between different filters to delimit them.

Full Example

aws ec2 describe-instances --filters "Name=tag-value,Values=mytagavalue" "Name=network-interface.addresses.private-ip-address,Values=10.*" --query 'Reservations[*].Instances[*].{InstanceId:InstanceId,PrivateDnsName:PrivateDnsName,State:State.Name, IP:NetworkInterfaces[0].PrivateIpAddress}'

Option 2) Via Query

Use the JMESPath starts_with() function to perform a partial string comparison of "10." against each network interface's private IP address.

Step By Step

First, select all instances:

Reservations[].Instances[]

Then pipe to filter for only instances containing network interfaces that have a private ip address starting with "10.":

| [? NetworkInterfaces [? starts_with(PrivateIpAddress, '10.')]]

Then select the fields just like you did before. This has not changed. (Note that you may want to select for all network interfaces instead of just the first.)

.{InstanceId:InstanceId,PrivateDnsName:PrivateDnsName,State:State.Name, IP:NetworkInterfaces[0].PrivateIpAddress}"

Full Example

aws ec2 describe-instances --filters "Name=tag-value,Values=mytagavalue" --query "Reservations[].Instances[] | [? NetworkInterfaces [? starts_with(PrivateIpAddress, '10.')]].{InstanceId:InstanceId,PrivateDnsName:PrivateDnsName,State:State.Name, IP:NetworkInterfaces[0].PrivateIpAddress}"

Further Reading

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM