Blogs

Scripting How-To: Make template-based configuration changes using Python

By Erdem posted 08-06-2015 04:53

  

Make Template-based Configuration Changes

 

You can make template-based configuration changes using Python. The jnpr.junos.utils.config module provides a Config.load() method that enables Jinja2-based template changes. You indicate the template file and a Python dictionary of variable name/values.

 

1 Config.load( template_path=path_to_file, template_vars=dictionary_of_variables )

 

Template Procedure

Assume that you have a template file called "system.conf" that contains the following template: 
 
1 system {
2   host-name {{ host_name }};
3   domain-name {{ domain_name }};
4 }

 

Load this template change using the following Python by importing the Config utility widget and binding it to a Device variable:

1 >>> from jnpr.junos.utils.config import Config
2

>>> cu = Config(dev)

 

Define your template variables in a Python dictionary.
 
IMPORTANT: It is critical that the dictionary keys (names) match the variables defined in the Jinj2a template (the names inside the double-braces).

 

1 >>> myvars = {}
2 >>> myvars['host_name'] = 'jeremy'
3 >>> myvars['domain_name'] = 'homelab.net'

 

Finally, load the changes onto the device using the Config.load() method:

 

1 >>> cu.load(template_path='system.conf', template_vars=myvars)

 

You can check the difference between the running configuration and the candidate configuration using the Config.pdiff() method:

 

1 [edit system]
2 -  host-name junos;
3 +  host-name jeremy;
4 -  domain-name wfs.com;
5 +  domain-name homelab.net;

 

The Config.load() method is a very versatile method for loading both static and template based content.  The content can come from Python variables or files. For documentation on the Config.load() method, enter help(Config.load) at the Python shell.

 

Of particular note is how Config.load() determines the format of the change. You can make changes to the Junos OS configuration using one of three formats:

 

  • text
  • XML
  • set

The set format was added to Junos OS 11.3 Release or later. You can override the auto-detect of format by using the format option.

 

The Config.load() only loads the changes into the candidate configuration, but does not commit the changes. To commit the changes, you use the Config.commit() method.


#overview
#How-To
#Python
#junospyez