I'm working on an ansible project for network troubleshooting, and I'm trying to set the ansible_network_os
variable automatically. I have an OS-agnostic python script that uses paramiko to run a show ver
command on routers, then returns a variable corresponding to the detected OS. The problem comes when I try to actually set the variable in the playbook.
Since ansible_network_os has not been set yet, the hosts
variable needs to be set to localhost
for this task. In the task, I'm looping over the network devices' IP addresses (item[0]) and the corresponding variables returned from the python script (item[1]). Using the zip() function, they're combined into one list for simultaneous traversal:
- name: Setting network variable...
set_fact:
hostvars[{{item[0]}}].ansible_network_os: "{{ item[1] }}"
loop: "{{ groups['targets']|zip(device_os.stdout_lines)|list }}"
This gives the error msg: The variable name 'hostvars[172.16.1.X].ansible_network_os' is not valid. Variables must start with a letter or underscore character, and contain only letters, numbers and underscores.
where X is any number 1-10 that corresponds to the device's internal IP.
I understand what the problem is, but I'm struggling to find a solution or workaround. What is the best way to set the value of a hostvars var dynamically like this?