Skip to content

Instantly share code, notes, and snippets.

@tgerla
Last active August 29, 2015 14:16
Show Gist options
  • Save tgerla/815362e34fb7c3bb988f to your computer and use it in GitHub Desktop.
Save tgerla/815362e34fb7c3bb988f to your computer and use it in GitHub Desktop.
# do you need this?
from jinja2 import contextfilter
class FilterModule(object):
''' Extra filters '''
def filters(self):
return {
'sort_hosts': self.sort_hosts,
}
def sort_hosts(self, hosts_list, hostvars, key):
hosts_list.sort(key = lambda x: hostvars[x][key])
return hosts_list
---
- hosts: localhost
tasks:
- command: echo {{ item }}
delegate_to: "{{ item }}"
with_items: "{{ groups['sorted']|sort_hosts(hostvars, 'idx') }}"
[sorted]
two ansible_connection=local idx=2
one ansible_connection=local idx=1
three ansible_connection=local idx=3
four ansible_connection=local idx=4
Timothys-MacBook-Pro:ansible-test tgerla$ ansible-playbook -i inventory -c local test-ordering.yml
PLAY [localhost] **************************************************************
GATHERING FACTS ***************************************************************
ok: [localhost]
TASK: [command echo {{ item }}] ***********************************************
changed: [localhost] => (item=one)
changed: [localhost] => (item=two)
changed: [localhost] => (item=three)
changed: [localhost] => (item=four)
PLAY RECAP ********************************************************************
localhost : ok=2 changed=1 unreachable=0 failed=0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment