I want to take different sligthly routes in a playbook based on the particular remote. All remotes are in the same hosts group.
I am trying to do this by setting a fact based on the ansible_fqdn value.
Based on that fact ('keycloak' in my example here) I am including different tasks files.
First of all, throw out the second, because the strings that are “when:” expressions are already being evaluated in a Jinja2 context, so the mustaches shouldn’t be there.
In the first option, on this line:
when: ansible_fqdn == VM-0213.step.zrz.internal
the “ansible_fqdn” part is okay, but the expression on the right-hand side “==” should be a string. Instead it’s the value of the variable “VM” minus the octal number 0213’s missing attribute “step”'s missing attribute “zrz”'s missing attribute “internal”.
Or, better yet in my opinion, set the default value for “level” in group_vars/<name_of_group>.yml, then for hosts which need a different “level” set that in an appropriately named host_vars file, like host_vars/VM-0213.step.zrz.internal.yml.
This let’s you expresses facts about hosts as data rather than as results of expressions in set_fact or other tasks, task which you no longer need to run.
does not create any error in the set_fact TASK. It does not set anything either unfortunately. Which, thinking of it, seems logical as we just compare the string ansible_fqdn with another string and not the value of the variale {{ ansible_fqdn }}. so that seems to be a dead end.
the second option seems too complex for my current scenario. I am trying to gather all variables into a singe place. And having to create a host_vars/.yml file for each host on each execution contradicts that a bit too much.
use *set_fact" if you want to 'instantiate' the variable (put the
variable into the *hostvars*). You can omit *set_fact* if you don't
need hostvars.*.level. For example, the play
As a result, the code is cleaner. Also the concentration of data into
a single point of failure (a dictionary and assignment isolated in
*vars*) makes the code more robust.
This indicates that your inventory_hostname and your ansible_fqdn are not the same, which can certainly be the case.
But Vladimir Botka is correct, and so is your intuition, that you should have all these variables in the same place. However, that place shouldn’t be in your tasks:.