Cisco

Ansible 使用 json 參數填充基於 json 參數的變數

  • December 30, 2021

我有一個包含 json 的變數:

{
   "ansible_facts": {
       "ansible_network_resources": {
           "interfaces": [
               {
                   "description": "*** - LOCAL A - ***",
                   "enabled": true,
                   "name": "FastEthernet0"
               },
               {
                   "description": "*** - LOCAL B - ***",
                   "enabled": true,
                   "name": "GigabitEthernet1/0/1"
               },
               {
                   "description": "*** - LOCAL C - ***",
                   "enabled": true,
                   "name": "FastEthernet1"
               }
           ]
       }
   }
}

當描述包含某個單詞時,我需要用介面名稱填充一個變數。

Q:當描述中包含某個單詞時,用介面名稱填充一個變數。

答:例如

   - set_fact:
       result: "{{ ansible_facts.ansible_network_resources.interfaces|
                  selectattr('description', 'search', pattern)|
                  map(attribute='name')|
                  list }}"
     vars:
       pattern: "LOCAL A"

 result:
 - FastEthernet0

   - set_fact:
       result: "{{ ansible_facts.ansible_network_resources.interfaces|
                   selectattr('description', 'search', pattern)|
                   map(attribute='name')|
                   list }}"
     vars:
       pattern: "LOCAL"

 result:
 - FastEthernet0
 - GigabitEthernet1/0/1
 - FastEthernet1

引用自:https://serverfault.com/questions/1088583