2

I have a list of commands to be sent to a Juniper router. How can I sort my list by the ip address at the end of the command?

From this, generated with set_fact and 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"
]

To this, ordered by the target 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"
]
Quake
  • 105
  • 1
  • 10

1 Answers1

2

Use sorted operation on list and make use of its key parameter to specify a function to be called on each list element prior to making comparisons.

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))

Output:

 ['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'] 
Austin
  • 25,759
  • 4
  • 25
  • 48
  • How can I use this within a playbook? – Quake Feb 21 '18 at 21:28
  • Please refer https://stackoverflow.com/questions/35139711/running-python-script-via-ansible . If not still answers your question, better ask as new SO-question. – Austin Feb 22 '18 at 18:04
  • I should have been more specific: How can I transfer the sorted list from python back into Ansible? Register isn't catching the the stdout from the script so the only solution I can think of is to have the script write the sorted list to a file and then have Ansible reimport the list. – Quake Feb 26 '18 at 16:21