Skip to content

Instantly share code, notes, and snippets.

@pwalkr
Last active July 23, 2022 18:02
Show Gist options
  • Save pwalkr/cdc9eddb6968dc5c91ee53c1848a49b4 to your computer and use it in GitHub Desktop.
Save pwalkr/cdc9eddb6968dc5c91ee53c1848a49b4 to your computer and use it in GitHub Desktop.
Docker swarm promotion based on inventory group membership
---
- 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
@pwalkr
Copy link
Author

pwalkr commented Jul 23, 2022

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:

- community.docker.docker_swarm_service:
    name: app
  delegate_to: '{{ groups.swarm_manager | random }}'
  run_once: true

This was largely an exercise in tuning a list of checks using when and loop - 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())

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