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

标签 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"
]

最佳答案

list上使用sorted操作,并利用其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'] 

关于python - Ansible - 按最后一个参数(IP 地址)对命令列表进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48911108/

相关文章:

Java Math.exp() 和 Python math.exp()

python - 如何从数据库列中的 python 数组中仅选择元素

python - 如何在ansible中设置多个ansible_python_interpreter变量

amazon-web-services - 具有 Cloudformation 动态引用的 AWS Proton 模板

python - 当我在 Python 中使用命令时,命令的运行与预期不同

javascript - 如何使用 javascript 获得相同的结果?

python - 如何将 "key = value;"对的字符串转换为 ansible 中的字典?

运行带有标签的 playbook 时 Ansible 注册变量为空

python - 如何在 jinja2 模板中显示日期时间字段? ( flask )

python - url_for 中的 flask jinja 宏变量