Junos Network Automation – Ansible + Jinja2 Template

June 16, 2020

Tweet This:
Share on LinkedIn:

By Cindy Jiang, Kovarus, Distinguished Solutions Architect

Recently, one of my customers asked me to create a template for a Juniper switch configuration using Red Hat Ansible and Jinja2. I thought it would be beneficial to put this quick blog together for anyone who wants to do the same. This blog walks you through the basic Red Hat Ansible modules and Junos network operating system J2 works. Lastly, a BGP configuration is used as an example.

Red Hat Ansible for Junos

Ansible has two sets of modules for Junos:

Setup Ansible and Juniper Environment

In my case, I am using NETCONF over SSH for Ansible of Juniper device.

For Ansible setup:

  • Install dependencies:
    • ncclient (python lib for netconf)
    • junos-eznc (python lib for junos)
  • Install Junos Ansible Galaxy Collection
    • junos_collection

For Juniper device setup:

  • NETCONF enabled on Juniper devices over SSH
    • Set system services netconf ssh

Config Templatization

The rule of thumb is to leverage Ansible modules/collections for config management, so that it provides better auditability and control. Depending on the complexity, using a Jinja2 template may be the quickest way to auto-generate the config. Here is how:

Three components:

  • Jinja2 — Basically the template configuration, it’s used to build and to generate any configuration.
  • YAML — Data input file which contains all variables (interface, IP…) human readable file, and it will be used by the Jinja2 template to generate the target configuration.
  • Junos PyEZ — Junos PyEZ enables you to manage Junos devices. It enables you to connect to devices running Junos using a serial console connection, telnet, or a NETCONF session over SSH. PyEZ will take the YAML Data file and the Jinja2 template as an input.

Junos BGP Config as Example

Jinja2 Template — bgp.j2: Variables are defined with “{{ }}”

YAML Data File:

Ansible Playbook – bgp.yml:
This playbook will take the j2 template and YAML data file, create the desired BGP configuration as “*.bgp.conf,” and place it into “render” sub-directory.

cjiang$ ansible-playbook bgp.yml

The final BGP configuration should look like this:

Once the configuration is generated, it can be sent to the Juniper device through NETCONF via the Ansible playbook with the Ansible module “juniper_junos_config.”

Hope this helps as a quick start for network engineers who haven’t touched network automation with Ansible yet!

Connect with me via Webex Teams or email at cjiang@kovarus.com.

Looking to learn more about modernizing and automating IT? We created the Kovarus Proven Solutions Center (KPSC) to let you see what’s possible and learn how we can help you succeed. To learn more about the KPSC go to the KPSC page.

Also, follow Kovarus on LinkedIn for technology updates from our experts along with updates on Kovarus news and events.