---
  - name: Add primary rabbit host to /etc/hostname
    lineinfile: dest=/etc/hosts line="{{ hostvars[groups.rabbitmq.0]['ansible_ssh_host'] }} {{ groups['rabbitmq'][0] }}"
  - name: Replace rabbitmq cookie with a common value
    template:
        dest=/var/lib/rabbitmq/.erlang.cookie
        src=erlang.cookie.j2
        backup=yes
        group=rabbitmq
        owner=rabbitmq
        mode=u+r
    register: cookie_replaced

  - name: Restart rabbitmq service to accept a new cookie
    service: name=rabbitmq-server state=restarted
    when: cookie_replaced|changed

  - name: Stop cluster
    shell: rabbitmqctl -n rabbit@$(hostname -f) stop_app
    when: cookie_replaced|changed

  - name: Reset cluster
    shell: rabbitmqctl -n rabbit@$(hostname -f) reset
    when: cookie_replaced|changed

  - name: Start first node of cluster
    shell: rabbitmqctl -n rabbit@$(hostname -f) start_app
    when: ( cookie_replaced|changed and inventory_hostname == "{{ groups['rabbitmq'][0] }}")

  - name: Trying to join all available nodes
    shell: "rabbitmqctl -n rabbit@$(hostname -f) join_cluster rabbit@{{ groups['rabbitmq'][0] }} "
    when: ( cookie_replaced|changed and inventory_hostname != "{{ groups['rabbitmq'][0] }}")

  - name: Start cluster
    shell: rabbitmqctl -n rabbit@$(hostname -f) start_app
    when: ( cookie_replaced|changed and inventory_hostname != "{{ groups['rabbitmq'][0] }}")

---
  - name: Add primary rabbit host to /etc/hostname
    lineinfile: dest=/etc/hosts line="{{ hostvars[groups.rabbitmq.0]['ansible_host'] }} {{ groups['rabbitmq'][0] }}"
  - name: Replace rabbitmq cookie with a common value
    template:
        dest=/var/lib/rabbitmq/.erlang.cookie
        src=erlang.cookie.j2
        backup=yes
        group=rabbitmq
        owner=rabbitmq
        mode=u+r
    register: cookie_replaced

  - name: Restart rabbitmq service to accept a new cookie
    service: name=rabbitmq-server state=restarted
    when: cookie_replaced|changed

  - name: Stop cluster
    shell: rabbitmqctl -n rabbit@$(hostname -f) stop_app
    when: cookie_replaced|changed

  - name: Reset cluster
    shell: rabbitmqctl -n rabbit@$(hostname -f) reset
    when: cookie_replaced|changed

  - name: Start first node of cluster
    shell: rabbitmqctl -n rabbit@$(hostname -f) start_app
    when: ( cookie_replaced|changed and inventory_hostname == "{{ groups['rabbitmq'][0] }}")

  - name: Trying to join all available nodes
    shell: "rabbitmqctl -n rabbit@$(hostname -f) join_cluster rabbit@{{ groups['rabbitmq'][0] }} "
    when: ( cookie_replaced|changed and inventory_hostname != "{{ groups['rabbitmq'][0] }}")

  - name: Start cluster
    shell: rabbitmqctl -n rabbit@$(hostname -f) start_app
    when: ( cookie_replaced|changed and inventory_hostname != "{{ groups['rabbitmq'][0] }}")

Use ansible_host in rabbitmq-cluster role
Use ansible_host in rabbitmq-cluster role
