Not sure if i really get what you are trying to do but you can check for the pre_task keyword. It's seems you are overengineering something. Try to think about idempotency
Ansible
# TODO
Let me try to reword it to make it clear.
I have 3 machines in my group. 1 of those will be the "leader". The others will be "joiners". The leader could already be initialized, so I need to check all machines to see if there is a leader already. If no Leader exists then any of the machines will do (the first) All of the machines that will join will need some data from the leader, so there will be a role task that will be delegated to the leader (ansible needs to know which host is the leader so as to be able to delegate to it)
This may sound complex but it is a very common pattern for distributed application setup.
idempotency doesn't play a role in this behaviour - the machines are all unique, but who knows what may have changed between ansible runs.
what you need is a pre_task to query all nodes and get the leader magic bit in a var using register, like below.
- name: Is docker manager
shell: docker info | grep 'Is Manager'
register: leader
- name: Get join string
shell: docker swarm join-token worker
when: "true in leader.stdout"
register: token
- name: Join a docker swarm as a worker
shell: "{{ token.stdout }}"
when: "true not in leader.stdout"
that is how I would go about getting a docker swarm setup, that any help?
Me either, but we have a role to bootstrap galara mysql and we just use the first host in a group
I thought that there might be a way to a custom facts (gather_facts) to all machines, and indicate leader/joiner status there, but I can't get the data to stick.
I think the idea to register the leader status during a dedicated task like Matt said is the better move.
You got this module if you want to create dynamic group during play :
https://docs.ansible.com/ansible/latest/collections/ansible/builtin/add_host_module.html
And during gather_facts, you could add your own custom facts :
https://docs.ansible.com/ansible/latest/playbook_guide/playbooks_vars_facts.html#adding-custom-facts
Bash script example returning json :
#!/bin/bash
leader_status=$(curl http://127.0.0.1/leader_status)
echo {\"leader\" : \"${leader_status}\"}
sounds like the same idea. So you use run_once
on a task?