---
- block:
  - name: Make sure we're not already using Docker swarm
    docker_swarm:
      state: absent
      force: true

  - name: Get docker_stack_info when docker is not running in swarm mode
    docker_stack_info:
    ignore_errors: true
    register: output

  - name: Assert failure when called when swarm is not running
    assert:
      that:
        - 'output is failed'
        - '"Error running docker stack" in output.msg'

  - name: Create a swarm cluster
    docker_swarm:
      state: present
      advertise_addr: "{{ansible_default_ipv4.address}}"

  - name: Get docker_stack_info when docker is running and not stack available
    docker_stack_info:
    register: output

  - name: Assert stack facts
    assert:
      that:
        - 'output.results | type_debug == "list"'
        - 'output.results | length == 0'

  - name: Template compose files
    template:
      src: "{{ item }}"
      dest: "{{ remote_tmp_dir }}/"
    with_items:
    - stack_compose_base.yml
    - stack_compose_overrides.yml

  - name: Install docker_stack python requirements
    pip:
      name: jsondiff,pyyaml

  - name: Create stack with compose file
    register: output
    docker_stack:
      state: present
      name: test_stack
      compose:
      - "{{ remote_tmp_dir }}/stack_compose_base.yml"

  - name: Assert test_stack changed on stack creation with compose file
    assert:
      that:
      - output is changed

  - name: Get docker_stack_info when docker is running
    docker_stack_info:
    register: output

  - name: assert stack facts
    assert:
      that:
        - 'output.results | type_debug == "list"'
        - 'output.results[0].Name == "test_stack"'
        - 'output.results[0].Orchestrator == "Swarm"'
        - 'output.results[0].Services == "1"'

  always:
  - name: Cleanup
    docker_swarm:
      state: absent
      force: true
