network-programmingansibleyamljuniperjunos-automation

Specific Targeting of Hosts Based on File Name


I am using ansible to send configuration ".set" files to a Junos OS devices using the "junos_install_config" module. I want to send specific files to specific hosts based on the names.

eg. I want to send the file "vMX1.set" to host vMX1, file "vMX2.set" to host vMX2 ect.

At the moment I am doing it like this:

---
name: Configure Junos Devices
hosts: all
roles:
    - Juniper.junos
connection: local
gather_facts: no
tasks:
   - name: Send to Device 1
     when: ansible_hostname == vMX1
     junos_install_config:
         host={{ inventory_hostname }}
         file=/home/usr/resources/vMX1.set
         overwrite=false
- name: Send to Device 2
     when: ansible_hostname == vMX2
     junos_install_config:
         host={{ inventory_hostname }}
         file=/home/usr/resources/vMX2.set
         overwrite=false

This works however is very time consuming and not very logical. If for example I have 50 config files and 50 devices, I would have to write 50 different tasks. Is there any way to automate this so that the playbook checks the name of the task and assigns the file with the corresponding name?

The host file looks like this

[vMXrouters]
vMX1 ansible_ssh_host=10.249.89.22
vMX2 ansible_ssh_host=10.249.89.190

Solution

  • Q: "Is there any way to automate this so that the playbook checks the name of the task and assigns the file with the corresponding name?"

    A: The playbook below should do the job

    - name: Configure Junos Devices
      hosts: all
      vars:
        list_of_devices: ['vMX1', 'vMX2']
      tasks:
        - name: "Send to {{ inventory_hostname }}"
          junos_install_config:
            host="{{ inventory_hostname }}"
            file="/home/usr/resources/{{ inventory_hostname }}.set"
            overwrite=false
          when: inventory_hostname in list_of_devices
          delegate_to: localhost
    

    The playbook is simpler if the group of the hosts is defined

    - name: Configure Junos Devices
      hosts: vMX_devices
      tasks:
        - name: "Send to {{ inventory_hostname }}"
          junos_install_config:
            host="{{ inventory_hostname }}"
            file="/home/usr/resources/{{ inventory_hostname }}.set"
            overwrite=false
          delegate_to: localhost
    

    (not tested)