---
# tasks for managing docker a swarm


# init swarm
- name: run init on a host
  command: docker swarm init
  args:
    creates: /var/lib/docker/swarm/state.json
  when: "ansible_nodename in swarm.managers"
  run_once: true

# get tokens
- name: get manager_token
  command: docker swarm join-token manager -q
  register: manager_token
  when: "ansible_nodename in swarm.managers"
  run_once: true
  changed_when: False

- name: get worker_token
  command: docker swarm join-token worker -q
  register: worker_token
  when: "ansible_nodename in swarm.managers"
  run_once: true
  changed_when: False

#- debug: var=manager_token

# add hosts to swarm
- name: adding manager to swarm
  command: docker swarm join --token={{manager_token.stdout}} {{swarm.managers[0]}}
  args:
    creates: /var/lib/docker/swarm/state.json
  when: "ansible_nodename in swarm.managers"

- name: adding worker to swarm
  command: docker swarm join --token={{worker_token.stdout}} {{swarm.managers[0]}}
  args:
    creates: /var/lib/docker/swarm/state.json
  when: "ansible_nodename in swarm.workers"

# remove hosts from swarm
- name: remove hosts from swam if found in remove list
  command: docker swarm leave
  args:
    removes: /var/lib/docker/swarm/state.json
  when: "ansible_nodename in swarm.removed"

# swarm config
- name: get history limit
  command: docker info --format '{% raw %}{{json .Swarm.Cluster.Spec.Orchestration.TaskHistoryRetentionLimit}}{% endraw %}'
  register: history_limit
  run_once: true
  changed_when: False

- debug: var=history_limit.stdout
  run_once: True

- name: set history limit
  command: docker swarm update --task-history-limit {{swarm.history}}
  when:
    - "ansible_nodename in swarm.managers"
    - 'swarm.history != history_limit.stdout|int'
  run_once: true
