So i am try to learn how to do loops in the playbook :
So suppose for example i wanted to look through all hosts get their public key and add on all other nodes, So they can have password less access. This is the best example i could think of , doing loops in playbook. This should work in template but how do i do in playbook. (yml)
Don't believe you can do this in the playbooks themselves. (Think there was
some talk of maybe allowing playbooks to be templated... don't think that
ever happened.)
{% for host in groups[$hosts] %}
- authorized_key:
key={{hostvars[host]['ansible_ssh_host_key_rsa_public']}}
{% endfor %}
Don't believe you can do this in the playbooks themselves. (Think there was
some talk of maybe allowing playbooks to be templated... don't think that
ever happened.)
Yeah, this is a terrible idea because if you do that, your playbooks
stop being valid data, and you can't just parse them by arbitrary
software.
Thanks, This is helpful… Is there an example i can see (to populate $all_my_keys from all nodes) , Yes using templates was my last option, i just wanted to explore other possibilities.
Either in a file specified by vars_files or in a file named
group_vars/all alongside your playbook or group_vars/groupname, I
would define something like so:
where $hosts is my group of servers im working on. So instead of putting in
a list how do i create a list of all hosts this playbook is running on.
Not so much.
However, you don't typically need that kind of loop as you are already
looping over those hosts for connectivity.
delegate_to and local_action are more natural in this case.
But in case you do want it, the following is available.
${groups.all} or ${groups.webservers} etc
Just be aware that if using that inside a play, it will still get
executed once for every host in that play, so don't use it where you
really meant local_action or delegate_to
Sorry, this is probably a bit incoherrent -- I would understand much
better if we were talking about a specific use case.
So basically how do people do loop in a loop, Like playbook is looping through all the hosts in group , 1 by 1 , but for each node i want to again loop through the entire group and get something from all nodes and do it on 1 node.
I want to use the “with_random_choice” and make it use all the hosts in the group the playbook in running on. Then this will select randomly 1 node, Then in template i just want to use this random nodes internal IP.
How best can i achieve this, As this will give a fairly good understanding how to do things like this.
With random choice will select a random string element, but that
variable you select is namespaced, not a global or anything like that.
Thus you can't currently randomly select a host.
You can however assign a random probability that you select the host
(may have to write a better filter plugin to do this), which is
probably not what you want.
I'll think about syntax about how we could possibly make that cleaner.