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

1 Answer 1

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'] 
Sign up to request clarification or add additional context in comments.

3 Comments

How can I use this within a playbook?
Please refer stackoverflow.com/questions/35139711/… . If not still answers your question, better ask as new SO-question.
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.