I have a script that I run at the start of my first play like this.
- hosts: localhost
local_action: command python runScript.py
It gnerates me a file in roles/abc/vars/main.yml which looks like this.
newHosts:
- hostIP: 192.168.1.23
filename: file1
- hostIP: 192.168.1.24
filename: file2
Then I call the role by
roles:
- { role: abc }
in that role, I’m trying to add those hosts to inventory_host as well as in the group by doing this:
add_host: hostname= {{ item.hostIP }} groups=newHosts filename= {{ item.filename }}
with_items: newHosts
The problem is that the first time when I run this play; the script runs and generates the file and when the role is called it gives me the error
fatal: [127.0.0.1] => One or more undefined variables: ‘unicode object’ has no attribute ‘hostIP’
FATAL: all hosts have already failed – aborting
which is logical because the file roles/abc/var/main.yml didn’t exist in the beginning. The second time when I run the playbook. it runs without any problem.
So, can you guide me how can I add the hosts from a file which is generated at the run-time and use it in the same play?
Thanking you in anticipation.
Warm Regards,
Fazal-e-Rehman Khan
Hi
I have a script that I run at the start of my first play like this.
- hosts: localhost
local_action: command python runScript.py
It gnerates me a file in roles/abc/vars/main.yml which looks like this.
newHosts:
- hostIP: 192.168.1.23
filename: file1
- hostIP: 192.168.1.24
filename: file2
Then I call the role by
roles:
- { role: abc }
in that role, I'm trying to add those hosts to inventory_host as well as in the
group by doing this:
add_host: hostname= {{ item.hostIP }} groups=newHosts filename= {{
item.filename }}
with_items: newHosts
The problem is that the first time when I run this play; the script runs and
generates the file and when the role is called it gives me the error
fatal: [127.0.0.1] => One or more undefined variables: 'unicode object' has no
attribute 'hostIP'
FATAL: all hosts have already failed -- aborting
which is logical because the file roles/abc/var/main.yml didn't exist in the
beginning. The second time when I run the playbook. it runs without any
problem.
Well - vars_files are read very early on during execution of
ansible-playbook. So that's why it fares better second time around.
So, can you guide me how can I add the hosts from a file which is generated at
the run-time and use it in the same play?
It sounds like you will be better off with a dynamic inventory - i.e.
have a look at http://docs.ansible.com/developing_inventory.html
By the sound of it you have most of what you need already, you just
need to make sure that your python script outputs an inventory in JSON format
Hope this helps