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

  - name: Try to get docker_node_info when docker is not running in swarm mode
    docker_node_info:
    ignore_errors: yes
    register: output

  - name: assert failure when called when swarm is not in use or not run on manager node
    assert:
      that:
         - 'output is failed'
         - 'output.msg == "Error running docker swarm module: must run on swarm manager node"'

  - name: Create a Swarm cluster
    docker_swarm:
      state: present
      advertise_addr: "{{ansible_default_ipv4.address | default('127.0.0.1')}}"
    register: output

  - name: assert changed when create a new swarm cluster
    assert:
      that:
         - 'output is changed'
         - 'output.actions[0] | regex_search("New Swarm cluster created: ")'
         - 'output.swarm_facts.JoinTokens.Manager'
         - 'output.swarm_facts.JoinTokens.Worker'

  - name: Try to get docker_node_info when docker is running in swarm mode and as manager
    docker_node_info:
    register: output

  - name: assert reading docker swarm node facts
    assert:
      that:
         - 'output.nodes | length > 0'
         - 'output.nodes[0].ID is string'

  - name: Try to get docker_node_info using the self parameter
    docker_node_info:
      self: yes
    register: output

  - name: assert reading swarm facts with list of nodes option
    assert:
      that:
         - 'output.nodes | length == 1'
         - 'output.nodes[0].ID is string'

  - name: Get local docker node name
    set_fact:
      localnodename:  "{{ output.nodes[0].Description.Hostname }}"


  - name: Try to get docker_node_info using the local node name as parameter
    docker_node_info:
      name: "{{ localnodename }}"
    register: output

  - name: assert reading reading swarm facts and using node filter (random node name)
    assert:
      that:
         - 'output.nodes | length == 1'
         - 'output.nodes[0].ID is string'

  - name: Create random name
    set_fact:
      randomnodename: "{{ 'node-%0x' % ((2**32) | random) }}"

  - name: Try to get docker_node_info using random node name as parameter
    docker_node_info:
      name: "{{ randomnodename }}"
    register: output

  - name: assert reading reading swarm facts and using node filter (random node name)
    assert:
      that:
         - 'output.nodes | length == 0'

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