Last active
July 23, 2022 18:02
-
-
Save pwalkr/cdc9eddb6968dc5c91ee53c1848a49b4 to your computer and use it in GitHub Desktop.
Docker swarm promotion based on inventory group membership
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
--- | |
- hosts: swarm_manager | |
gather_facts: no | |
tasks: | |
- name: run pre-flight checks | |
fail: | |
msg: '{{ checks[item].message }}' | |
register: r | |
# abort after first failure - https://medium.com/opsops/how-to-break-from-the-loop-in-ansible-1e8ebb92be0d | |
when: not (r.failed|d(false)) and checks[item].condition | |
# This is a much less verbose way to loop | |
loop: '{{ checks.keys() }}' | |
vars: | |
# List of pre-flight checks - key shows up in loop | |
checks: | |
'target defined': | |
condition: '{{ not target is defined }}' | |
message: "This play requires '--extra-vars target=host' to promote" | |
'swarm managers': | |
condition: '{{ target | default("") not in groups.swarm_manager }}' | |
message: "Target must be in the 'swarm_manager' inventory group" | |
'only manager': | |
condition: '{{ target | default("") == groups.swarm_manager[0] }}' | |
message: 'Target must not be the only (first) manager' | |
run_once: yes | |
- name: promote | |
ansible.builtin.command: 'docker node promote {{ target }}' | |
register: promotion | |
changed_when: '"already" not in promotion.stdout' | |
run_once: yes |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This playbook promotes a docker-swarm node to manager status.
The
swarm_manager
group indicates a list of managers where swarm commands can be run. E.g. to deploy a service, you could:This was largely an exercise in tuning a list of checks using
when
andloop
- expanding on medium.com/opsops/how-to-break-from-the-loop-in-ansible, I wanted a complex loop WITHOUT complex terminal output. By default ansible prints a whole json object of each item in the loop. With the above, the actual loop list is just a list of keys (dynamically pulled with.keys()
)