Skip to content

Instantly share code, notes, and snippets.

@halberom
Last active October 1, 2019 12:57
Show Gist options
  • Save halberom/b36200260db3c54cbd56 to your computer and use it in GitHub Desktop.
Save halberom/b36200260db3c54cbd56 to your computer and use it in GitHub Desktop.
ansible - example of dynamic even/odd groups
# requirement
# given 2 groups (A and B), target 50% of each for code deploy
- hosts: localhost
tasks:
# this might need to be group_by or add_host
- set_fact:
even: "{{ groups['groupA'][::2] | union(groups['groupB'][::2] }}"
odd: "{{ groups['groupA'][1::2] | union(groups['groupB'][1::2] }}"
- hosts: even
roles:
- deploy something
- hosts: odd
roles:
- deploy something
# it may also be possible to do
#- hosts: even;odd
# serial: 50%
@jeanlouisferey
Copy link

Thanks for this trick.

I think it's not necessary to do set_fact (except to increase readibility):

- name: work on odd servers
  hosts: "{{ groups['web'][::2] | union(groups['database'][::2]) }}"
  tasks:
    - name: reboot odd servers
      debug:
        msg: "I will reboot odd server: {{ ansible_hostname}}"

- name: work on even servers
  hosts: "{{ groups['web'][1::2]  | union(groups['database'][1::2]) }}"
  tasks:
    - name: reboot even servers
      debug:
        msg: "I will reboot even server: {{ ansible_hostname}}"

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment