Skip to content

Instantly share code, notes, and snippets.

@Paulladium46
Last active February 9, 2024 04:02
Show Gist options
  • Select an option

  • Save Paulladium46/85d95a7264cd3fd502aed33853fa8e71 to your computer and use it in GitHub Desktop.

Select an option

Save Paulladium46/85d95a7264cd3fd502aed33853fa8e71 to your computer and use it in GitHub Desktop.
Ansible Playbook for Docker Swarm Node Rolling Updates

Ansible Playbook for Docker Swarm Node Rolling Updates

  • Feb 2024
  • Semaphore UI for Ansible v2.9.37

Objective:

  • create an Ansible Playbook that will go through a cluster of Docker Swarm hosts and serially update them in a graceful manner.

Perspective

  • I'm new to Ansible, so had, and still have, a lot to learn
  • Lots of ways to improve this, and I expect to continue working on it.

Challenges

  • Lots of challenges due to my inexperience - below are a few I'm highlighting

How do I register a variable and persist it between plays targeting different host groups?

Short vs long names

  • I use FQDNs for many things in my homelab, and docker swarm just wants the short name of the node for control commands.
  • So I added the ansible_host= to each host to cover this.

Other Resources Leveraged


Sample Inventory Content

[swarm_workers]
worker1 ansible_host=worker1.mydomain
worker2 ansible_host=worker2.mydomain
worker3 ansible_host=worker3.mydomain

[swarm_managers]
manager1 ansible_host=manager1.mydomain
manager2 ansible_host=manager2.mydomain
manager3 ansible_host=manager3.mydomain

Ansible Playbook

---
- hosts: swarm_managers
  tasks:
  - name: Pick an online swarm manager node to execute swarm control commands 
    set_fact:
      active_mgr: "{{ ansible_play_hosts[0] }}"

- hosts: '{{ host_list }}'
  serial: 1

  tasks:

  - name: Drain Active host - Delegate to the chosen online swarm manager node
    shell: docker node update --availability drain '{{ inventory_hostname }}'
    delegate_to:  "{{ hostvars.manager1.active_mgr }}"

  - name: apt dist-upgrade
    become: yes
    apt:
      update_cache: yes
      upgrade: dist
      autoremove: yes

  - name: Reboot the machine
    become: yes
    ansible.builtin.reboot:
      pre_reboot_delay: 60
      msg: "Rebooting machine in 60 seconds - Ansible"

  - name: Set Host to Active  - Delegate to the chosen online swarm manager node
    shell: docker node update --availability active '{{ inventory_hostname }}'
    delegate_to:  "{{ hostvars.manager1.active_mgr }}"

  - name: Pause for 60 seconds to allow swarm settling
    ansible.builtin.pause:
      seconds: 60
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment