I am new to Ansible and trying to get my hands dirty on playbooks. I wrote an yaml file to use a variable from one host tasks to another. Here is my code ( logically this code may not make sense in real world, I am trying to understand features in Ansible )
I have tried with your suggestion and got following error.
fatal: [172.19.251.173]: FAILED! => {"msg": "The conditional check
'hostvars['hostname1']['ansible_facts']['distribution'] == 'CentOS''
failed. The error was: error while evaluating conditional
(hostvars['hostname1']['ansible_facts']['distribution'] == 'CentOS'):
\"hostvars['hostname1']\" is undefined\n\n
shows all the hosts in my inventory file, so I believe my playbook has access to all hosts. To hash out issue with inventory file, I modified my code as below.
The distribution variable is a gather facts variable, and when you run against hostname2 only that variable is not accessible because Ansible has not state between playbook run.
One solution would be to use fact caching, or the easiest, just run gather facts on hostname1 first in the same playbook by adding following code before you play above.
If I understand you correctly than try to do this. Make a folder host_var in your inventory folder. Than make a file with the exact same name as your host inside it,
something like: inventory/host_var/host1.yaml
Inside that file you'll put the vars and those you can you use global for that host.
Thanks for your time and efforts to help me out with the issue. I understood the mistak. I missed out making changes in the config file as described in below link