在本教程中,我们将看到如何使用该F
对象对host进行高级过滤。让我们首先启动nornir并查看inventory:
from nornir import InitNornir from nornir.core.filter import F nr = InitNornir(config_file="advanced_filtering/config.yaml")
%cat advanced_filtering/inventory/hosts.yaml
--- cat: groups: - terrestrial - mammal data: domestic: true diet: omnivore additional_data: lifespan: 17 famous_members: - garfield - felix - grumpy bat: groups: - terrestrial - mammal data: domestic: false fly: true diet: carnivore additional_data: lifespan: 15 famous_members: - batman - count chocula - nosferatu eagle: groups: - terrestrial - bird data: domestic: false diet: carnivore additional_data: lifespan: 50 famous_members: - thorondor - sam canary: groups: - terrestrial - bird data: domestic: true diet: herbivore additional_data: lifespan: 15 famous_members: - tweetie caterpillaer: groups: - terrestrial - invertebrate data: domestic: false diet: herbivore additional_data: lifespan: 1 famous_members: - Hookah-Smoking octopus: groups: - marine - invertebrate data: domestic: false diet: carnivore additional_data: lifespan: 1 famous_members: - sharktopus
%cat advanced_filtering/inventory/groups.yaml
--- mammal: data: reproduction: birth fly: false bird: data: reproduction: eggs fly: true invertebrate: data: reproduction: mitosis fly: false terrestrial: {} marine: {}
如您所见,我们已经建立了具有不同属性的动物的集合。通过该F
对象,您只需在两个下划线之间加上魔术方法的名称即可访问每种类型的魔术方法。例如,如果您要检查列表中是否包含特定元素,则只需添加即可__contains
。让我们使用此功能来检索属于该组的所有动物bird
:
birds = nr.filter(F(groups__contains="bird")) print(birds.inventory.hosts.keys())
dict_keys(['eagle','canary'])
我们还可以F
通过添加前缀来反转对象~
:
not_birds = nr.filter(~F(groups__contains="bird")) print(not_birds.inventory.hosts.keys())
dict_keys([‘cat’, ‘bat’, ‘caterpillaer’, ‘octopus’])
我们还可以组合F
对象并分别使用符号&
和|
(管道)执行AND和OR操作:
domestic_or_bird = nr.filter(F(groups__contains="bird") | F(domestic=True)) print(domestic_or_bird.inventory.hosts.keys())
dict_keys(['cat','eagle','canary'])
domestic_mammals = nr.filter(F(groups__contains="mammal") & F(domestic=True)) print(domestic_mammals.inventory.hosts.keys())
dict_keys(['cat'])
如预期的那样,您可以组合所有符号:
flying_not_carnivore = nr.filter(F(fly=True) & ~F(diet="carnivore")) print(flying_not_carnivore.inventory.hosts.keys())
dict_keys(['canary'])
您还可以通过添加两个下划线和要访问的数据,以与访问魔术方法相同的方式访问嵌套数据。您可以根据需要继续构建,甚至可以访问嵌套数据的魔术方法。例如,让我们获得寿命大于或等于15的动物:
long_lived = nr.filter(F(additional_data__lifespan__ge=15)) print(long_lived.inventory.hosts.keys())
dict_keys(['cat','bat','eagle','canary'])
有两个额外的功能可以帮助您处理列表。any
和all
。这些功能使您可以发送元素列表,并获取具有任何成员或所有成员的对象。例如:
marine_and_invertebrates = nr.filter(F(groups__all=["marine", "invertebrate"])) print(marine_and_invertebrates.inventory.hosts.keys())
dict_keys(['octopus'])
bird_or_invertebrates = nr.filter(F(groups__any=["bird", "invertebrate"])) print(bird_or_invertebrates.inventory.hosts.keys())
dict_keys(['eagle', 'canary', 'caterpillaer', 'octopus'])