【问题标题】:Ansible - Sort a list of commands by the last argument, an IP addressAnsible - 按最后一个参数(IP 地址)对命令列表进行排序
【发布时间】:2018-02-22 01:45:31
【问题描述】:

我有一个要发送到瞻博网络路由器的命令列表。如何按命令末尾的 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"
]

【问题讨论】:

    标签: python ansible jinja2


    【解决方案1】:

    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'] 
    

    【讨论】:

    • 如何在剧本中使用它?
    • 请参考stackoverflow.com/questions/35139711/…。如果仍然没有回答您的问题,最好作为新的 SO 问题提出。
    • 我应该更具体一点:如何将排序列表从 python 传输回 Ansible? Register 没有从脚本中捕获标准输出,所以我能想到的唯一解决方案是让脚本将排序列表写入文件,然后让 Ansible 重新导入列表。
    猜你喜欢
    • 2020-01-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-25
    • 2020-09-28
    • 2011-09-09
    • 2016-10-01
    • 2015-05-31
    相关资源
    最近更新 更多