Search code examples
ansiblejmespath

How to filter multiple key name start with similar string key using Jmespath?


I have below json from which i want to filter all mac address start with key macaddress_ using jmespath how to achieve this ?

{
  "facts_hash": {
    "macaddress_em1": "44:a8:42:27:c7:ba",
    "netmask_em1": "255.255.255.0",
    "mtu_em1": "1500",
    "macaddress_em2": "44:a8:42:27:c7:bb",
    "mtu_em2": "1500",
    "macaddress_em3": "44:a8:42:27:c7:bc",
    "mtu_em3": "1500",
    "macaddress_em4": "44:a8:42:27:c7:bd",
    "mtu_em4": "1500",

  }
}

Thanks


Solution

  • Instead of json_query, it's possible to select the matching keys and extract the values. For example

        - debug:
            msg: "{{ my_keys|
                     map('extract', facts_hash)|
                     list }}"
          vars:
            my_keys: "{{ facts_hash.keys()|
                         select('match', '^macaddress_(.*)$')|
                         list }}"
    

    gives

        "msg": [
            "44:a8:42:27:c7:ba",
            "44:a8:42:27:c7:bb",
            "44:a8:42:27:c7:bc",
            "44:a8:42:27:c7:bd"
        ]