Ansible - 按最后一个参数(IP地址)对命令列表进行排序

时间:2018-02-21 16:41:43

标签: python ansible jinja2

我有一个要发送到Juniper路由器的命令列表。如何通过命令末尾的ip地址对列表进行排序?

由此生成,使用set_fact和with_items

生成
"command_list": [
    "show bgp neighbor 1.1.1.1",
    "show bgp neighbor 2.2.2.2",
    "show bgp neighbor 3.3.3.3",
    "show route receive-protocol bgp 1.1.1.1",
    "show route receive-protocol bgp 2.2.2.2",
    "show route receive-protocol bgp 3.3.3.3",
    "show route advertising-protocol bgp 1.1.1.1",
    "show route advertising-protocol bgp 2.2.2.2"
    "show route advertising-protocol bgp 3.3.3.3"
]

对此,按目标IP排序。

"command_list": [
    "show bgp neighbor 1.1.1.1",
    "show route receive-protocol bgp 1.1.1.1",
    "show route advertising-protocol bgp 1.1.1.1",
    "show bgp neighbor 2.2.2.2",
    "show route receive-protocol bgp 2.2.2.2",
    "show route advertising-protocol bgp 2.2.2.2"
    "show bgp neighbor 3.3.3.3",   
    "show route receive-protocol bgp 3.3.3.3",        
    "show route advertising-protocol bgp 3.3.3.3"
]

1 个答案:

答案 0 :(得分:2)

sorted上使用list操作并使用其key参数指定在进行比较之前在每个列表元素上调用的函数。

command_list = [
    "show bgp neighbor 1.1.1.1",
    "show bgp neighbor 2.2.2.2",
    "show bgp neighbor 3.3.3.3",
    "show route receive-protocol bgp 1.1.1.1",
    "show route receive-protocol bgp 2.2.2.2",
    "show route receive-protocol bgp 3.3.3.3",
    "show route advertising-protocol bgp 1.1.1.1",
    "show route advertising-protocol bgp 2.2.2.2",
    "show route advertising-protocol bgp 3.3.3.3"
]
def last(a):
    for i in reversed(a.split()):
        return i
print(sorted(command_list, key=last))

<强>输出

 ['show bgp neighbor 1.1.1.1',
 'show route receive-protocol bgp 1.1.1.1',
 'show route advertising-protocol bgp 1.1.1.1',
 'show bgp neighbor 2.2.2.2', 
 'show route receive-protocol bgp 2.2.2.2', 
 'show route advertising-protocol bgp 2.2.2.2',
 'show bgp neighbor 3.3.3.3',
 'show route receive-protocol bgp 3.3.3.3',
 'show route advertising-protocol bgp 3.3.3.3']