Applying Junos Configuration Automation

Embed Size (px)

Citation preview

  • 8/13/2019 Applying Junos Configuration Automation

    1/102

    Its day one and you have a job todo. Start using Junos automationtoday to manage and control theconguration of any Junos deviceso that it always complies withyour critical practices and policies.

    By Curtis Call

    Junos Automation Series

    DAY ONE: APPLYING JUNOSCONFIGURATION AUTOMATION

    By Curtis Call

  • 8/13/2019 Applying Junos Configuration Automation

    2/102

    Juniper Networks Day One booklets provide just the information you need on day one. They are

    written by subject matter experts and engineers who specialize in getting networks up and running.

    Look for other titles covering high-performance networking solutions at www.juniper.net/dayone.

    This book is available in both PDF and printed formats.

    Junos Automation Series

    Day One: Applying Junos Conguration AutomationThe Junos automation toolset is a standard part of the operating system available on all Junos

    platforms including routers, switches, and security devices. This booklet continues teaching the

    core concepts begun in the first two volumes of the Junos Automation Series.

    Commit scripts fill the third role of Junos automation by providing a way to add customized

    intelligence as part of the commit process used by Junos to validate all configuration changes.

    Junos executes the commit scripts automatically each time an administrator commits the

    configuration. Commit scripts can control the commit process in multiple ways ranging from simple

    warning messages to complex configuration changes based on the presence of configuration

    macros.

    Day One: Applying Junos Conguration Automation shows you how to:

    Understand the role of and possible uses for commit scripts. Provide feedback as part of the commit process through warning or syslog

    messages.

    Halt the commit process with error messages.

    Alter the configuration through commit scripts .

    Use configuration macros to simplify your configuration or to store specialized

    data.

    Create your own customized commit scripts.

    7100111

    #3

    The flexibility and power of Junos configuration is increased with theintroduction of commit scripts. This book provides a clear overviewand the detailed information required to take full advantage of thesescripts.

    Mike Benjamin, Distinguished Engineer, Global Crossing

  • 8/13/2019 Applying Junos Configuration Automation

    3/102

    Junos

    Automation Series

    Day One: Applying Junos

    Con guration Automation

    By Curtis Call

    Chapter 1: Introducing Commit Scripts 5

    Chapter 2: Commit Feedback and Control 19

    Chapter 3: Changing the Con guration 35

    Chapter 4: Con guration Macros 63

    Supplemental Junos automation information is available in the

    PDF version of this booklet:

    Appendix 77

  • 8/13/2019 Applying Junos Configuration Automation

    4/102

    2010 by Juniper Networks, Inc. All rightsreserved. Juniper Networks, the Juniper Net-works logo, Junos, NetScreen, and ScreenOS areregistered trademarks of Juniper Networks, Inc.in the United States and other countries. Junose isa trademark of Juniper Networks, Inc. All othertrademarks, service marks, registered trade-marks, or registered service marks are theproperty of their respective owners.

    Juniper Networks assumes no responsibility forany inaccuracies in this document. JuniperNetworks reserves the right to change, modify,transfer, or otherwise revise this publicationwithout notice. Products made or sold by JuniperNetworks or components thereof might becovered by one or more of the following patentsthat are owned by or licensed to Juniper Net-works: U.S. Patent Nos. 5,473,599, 5,905,725,5,909,440, 6,192,051, 6,333,650, 6,359,479,6,406,312, 6,429,706, 6,459,579, 6,493,347,6,538,518, 6,538,899, 6,552,918, 6,567,902,6,578,186, and 6,590,785.

    Day One Series Editor: Cathy GadeckiWriter: Curtis CallCopyeditor and Proong: Nancy KoerbelLiterary Management: Ames & Eames, Inc.Printed in the USA by Vervante Corporation.

    Version History: v1 January 2010 2 3 4 5 6 7 8 9 10

    About the AuthorCurtis Call is a Systems Engineer at JuniperNetworks and the author of the rst three Day

    One booklets in the Junos Automation Series. Heis JNCIE-M #43 and has eight years experienceworking with Junos devices.

    Authors AcknowledgmentsThe author would like to thank all those whohelped in the creation of this booklet: PatrickAmes and Nancy Koerbel and Cathy Gadeckiwere instrumental in bringing this project tofruit ion and helped make the content more

    instructional. Im also indebted to Roy Lee, the Junos Automation Product Line Manager, for hiscareful reviews and clarications on Junosautomation. Thank you all.

    A free PDF version of this booklet is available at:www.juniper.net/dayone.

    ii

  • 8/13/2019 Applying Junos Configuration Automation

    5/102

    Welcome to Day One

    Day One booklets help you to start quickly in a new topic with justthe information that you need on day one. The Day One series coversthe essentials with straightforward explanations, step-by-step instruc-tions, and practical examples that are easy to follow, while alsoproviding lots of references for learning more.

    Why Day One Booklets?

    Its a simple premise you want to use your Juniper equipment asquickly and effectively as possible. You dont have the time to readthrough a lot of different documents. You may not even know where

    to start. All you want to know is what to do on day one.Day One booklets let you learn from Juniper experts, so you not onlynd out how to run your device, but where the short cuts are, how tostay out of trouble, and what are best practices.

    What This Booklet Offers You

    This third booklet in the Junos Automation series helps you toautomate the commit process of your Junos device. Read it to

    learn how to use the Junos automation scripting toolset and howto to write your rst commit scripts.

    When youre done with this booklet, youll be able to:P Understand the role of and possible uses for commit scripts.P Provide feedback as part of the commit process through warning

    or syslog messages.P Halt the commit process with error messages.P Alter the conguration through commit scripts.P

    Use conguration macros to simplify your conguration or tostore specialized data.P Create your own customized commit scripts.

  • 8/13/2019 Applying Junos Configuration Automation

    6/102

    What You Need to Know Before Reading

    Before reading this booklet, you should be familiar with the basicadministrative functions of the Junos operating system. This includesthe ability to work with operational commands and to read, under-stand, and change the Junos conguration. The Day One booklets ofthe Junos Fundamentals series, and the training materials available onthe Fast Track portal, can help to provide this background (see the lastpage of this booklet for these and other references).

    Other things that you will nd helpful as you explore these pages:P Having access to a Junos device while reading this booklet is very

    useful as a number of practice examples reinforcing the conceptsbeing taught are included in these pages. Most of the examplesrequire creating or modifying a script and then running the scripton a Junos device in order to see and understand the effect.

    P The best way to edit SLAX scripts is to use a text editor on yourlocal PC or laptop and then to transfer the edited le to the Junosdevice using a le transfer application. Doing this requires access toa basic ASCII text editor on your local computer as well as thesoftware to transfer the updated script using scp or ftp.

    P While a programming background is not a prerequisite for usingthis booklet, a basic understanding of programming concepts isbenecial.

    P This is the third volume of the Junos Automation series. Readingthe previous volumes is recommended but not necessarily required.This booklet assumes you are familiar with the concepts of Junosautomation and the material covered in the previous publicationsof this Day One series.

    Supplemental Appendix

    If youre reading the print edition of this booklet, theres more pages

    available in the PDF version, which includes a supplemental appendix.Go to www.juniper.net/dayone and download the free PDF version ofthis booklet to get the additional content.

    NOTE Wed like to hear your comments and critiques. Please send us yoursuggestions by email at [email protected].

    iv

  • 8/13/2019 Applying Junos Configuration Automation

    7/102

    Chapter 1

    Introducing Commit Scripts

    Junos Automation Overview 6

    Commit Scripts 6

    Con guration/Storage 9

    Commit Script Boilerplate 10

    11

    16

    Boot-up Commit 17

    Commit Script Checklist 18

  • 8/13/2019 Applying Junos Configuration Automation

    8/102

    6 Day One: Applying Junos Con guration Automation

    The Junos automation toolset is a standard part of the Junos operatingsystem available on all Junos platforms including routers, switches, andsecurity devices. This booklet continues teaching the core concepts of

    Junos automation begun in the rst two volumes: Day One: Applying Junos Operations Automation and Day One: Applying Junos EventAutomation . The rst booklet explains the SLAX scripting language anddescribes how to use op scripts, one type of Junos automation script. Thesecond booklet explains how to automate events through event policiesand scripts. This booklet, the third of the Junos Automation Series,describes how commit scripts automate the commit process, givingadministrators control over what conguration is applied to their Junosdevice.

    Junos Automation Overview

    Junos automation enables an organization to embed its wealth of knowl-edge and experience of operations directly into Junos devices:

    n Business rules automation - enforces best practices and changesmanagement to avert human factors.

    n Provisioning automation - simplies and abstracts complex congu-rations to minimize errors.

    n Operations automation - customizes command output to streamlineoperation and troubleshooting.

    n Event automation - performs automatic changes and responses inreaction to observed events.

    Through automation, Junos empowers network operators to scale bysimplifying complex tasks, maximizing uptime, and optimizing opera-tional efciency.

    Commit Scripts

    The prior two booklets discussed the application of op and event scripts.An op script is a customized command that administrators can executefrom the CLI prompt (and other scripts can call) in the same way as astandard Junos command. Op scripts can gather and display desiredinformation, perform controlled conguration changes, or execute agroup of operational commands. Event scripts are used in conjunctionwith event policies to automate reactions to events.

  • 8/13/2019 Applying Junos Configuration Automation

    9/102

    Chapter 1: Introducing Commit Scripts

    Commit scripts ll the third role of Junos automation by providing away to add customized intelligence as part of the commit process.

    Junos executes the commit scripts automatically each time an admin-istrator commits the conguration. Commit scripts can control thecommit process in multiple ways ranging from simple warningmessages to complex conguration changes based on the presence ofconguration macros.

    Commit Script Examples

    A few examples of how commit scripts can control congurationinclude:

    n Verifying essential conguration hierarchies whenever a userchanges the conguration. If a user accidently deletes any of thesehierarchies the script can instruct Junos to halt the commitprocess and issue an error message. This prevents networkoutages caused by human error.

    n Checking for descriptions of interfaces or BGP peers at eachcommit time. An improperly formatted description can result in awarning message, advising the user to x it.

    n Reducing the number of statements required in complex congu-rations. Conguration macros can act as customer-standardizedconguration syntax and expand into complex congurationstructures at commit time.

    n Enforcing scaling limits for critical settings. For example, a scriptcan generate a commit error (or warning) when the congurationexceeds the maximum number of permitted peers.

    MORE? To see more script examples go to the online script library at www.juniper.net/scriptlibrary.

    Commit Process

    The Junos commit process not only enables administrators to previewall changes before performing a commit, it also enables Junos tovalidate the syntax and logic of the candidate conguration beforeapplying it. When a commit is requested, Junos rst performsinheritance on the candidate conguration by integrating any con-guration groups into their destination hierarchies and removing allinactive statements. The post-inheritance conguration is then

  • 8/13/2019 Applying Junos Configuration Automation

    10/102

    checked out by Junos for any conguration errors or warnings. Botherrors and warnings are displayed to the committing administrator,but errors also cause Junos to fail the commit.

    Commit scripts give users a way to customize the validation process oftheir congurations in accordance with their own practices andpolicies. Junos integrates commit scripts seamlessly into its commitprocess, allowing the scripts to check and modify the congurationprior to the nal verication performed by Junos. Figure 1.1 showswhere commit scripts t in the commit process:

    Figure 1.1 Commit Model with Commit Scripts

    The execution of commit scripts occurs after inheritance has beenperformed on the conguration, so all commit scripts are provided thepost-inheritance conguration at the start of their processing. Eachcommit script refers to this post-inheritance conguration as it deter-mines what actions, if any, need to be performed. A script can perform(the following) ve commit-specic actions:

    n Displaying a warning to the committing user (Chapter 2).

    8 Day One: Applying Junos Event Automation

    Cancel commit if any errorsare reported

    ExecuteCommitScripts

    Result

    Tree Result

    Tree Result

    Tree

    CandidateConfiguraiton

    CommitRequested

    Post-Inheritance

    Configuration

    CandidateConfigurations

    CheckoutConfiguration

    CommittedConfiguration

    Display warnings

    Log syslogmessages

    Changes

    Transientchanges

  • 8/13/2019 Applying Junos Configuration Automation

    11/102

    Chapter 1: Introducing Commit Scripts

    n Logging a message to the syslog (Chapter 2).n

    Generating a commit error and canceling the commit (Chapter 2).n Changing the conguration (Chapters 3 and 4).n Transiently changing the conguration (Chapters 3 and 4).

    Commit scripts communicate necessary actions to Junos by includinginstructions in their result tree. Each commit script is executedsequentially and its result tree is provided to Junos when the scriptterminates. Once all commit scripts have been executed, Junos thenprocesses all of the scripts instructions. Based on these instructions,

    Junos might halt the commit, display warning messages, or alter theconguration.

    If the commit process is not halted by a commit script, then Junosapplies all the commit script changes and performs its nal inspectionof the checkout conguration. For a conguration that passes allchecks, Junos activates the new conguration to the device.

    The placement of commit scripts within the commit process, and theirability to inject instructions to inuence that process, providesadministrators with exibility and complete control over the nalcongurations committed on Junos devices.

    Con guration/StorageAdministrators add new commit scripts by enabling them within theconguration and storing them on the Junos device in the /var/db/ scripts/commit directory. The command to enable new scripts is:set system scripts commit file example-commit-script.slax

    And the locations are:n Storage Location: /var/db/scripts/commitn Conguration Location: [edit system scripts com mit]

    NOTE Beginning in Junos 9.4, the Juniper EX Series began storing congu-rations in / config/db/scripts rather than /var/db/scripts . /var/db/scripts links to the new /config/db/scripts directory so les that arecopied into /var/db/scripts are still placed in the correct location.

    NOTE The load-scripts-from-flash conguration command changes thescript storage location from /var/db/scripts to /config/scripts . Ifyou are using this conguration statement, store the commit scripts in/config/scripts/commit .

  • 8/13/2019 Applying Junos Configuration Automation

    12/102

    10 Day One: Applying Junos Con guration Automation

    Only super-users, users with the all permission bit, or users that havebeen given the maintenance permission bit are permitted to enable ordisable Junos commit scripts in the conguration.

    ALERT! The Junos management process executes commit scripts with rootpermissions, not the permission level of the committing user. If theuser has the necessary access permissions to commit the conguration,then Junos performs all actions of the congured commit scripts,regardless of the privileges of the committing user.

    NOTE In devices with multiple routing-engines (including EX4200 VirtualChassis), each routing engine performs the commit process separately.

    Because of this, the script le must be copied into the commit scriptdirectory, and enabled on every routing-engine. Typically the congu-ration of all routing-engines is done automatically through congura-tion synchronization, but if the congurations are not synchronizedbetween routing-engines then the script must be enabled on all routing-engines manually.

    allow-transients

    Commit scripts can perform conguration changes that affect theoperation of the Junos device but do not appear in the congurationle. These changes are referred to as transient conguration changesand can be used in conjunction with conguration macros to createcustom conguration syntax. Transient conguration changes arediscussed in Chapters 3 and 4 and are not permitted by default. Toallow them, enter the following conguration command:set system scripts commit allow-transients

    Commit Script Boilerplate

    When writing Junos automation scripts, it is always best to work fromthe standard boilerplate. This greatly simplies script writing, as there

    is no need to memorize the necessary name-space URLs. Instead, justcopy and paste the boilerplate and add your script code within it. Theboilerplate used for writing commit scripts is similar to the boilerplateused for op and event scripts with two signicant differences that arediscussed in following sections. Here is the boilerplate that should beused when writing commit scripts:version 1.0;

    ns junos = "http://xml.juniper.net/junos/*/junos";ns xnm = "http://xml.juniper.net/xnm/1.1/xnm";

  • 8/13/2019 Applying Junos Configuration Automation

    13/102

    Chapter 1: Introducing Commit Scripts

    ns jcs = "http://xml.juniper.net/junos/commit-scripts/1.0";

    import "../import/junos.xsl";

    match configuration {

    /* Your script code goes here */

    }

    version: While version 1.0 is currently the only available version of theSLAX language, the version line is required at the beginning of all Junosscripts.

    ns: a ns statement denes a namespace prex and its associatednamespace URL. The following three namespaces must be included in all

    Junos scripts:n ns junos = "http://xml.juniper.net/junos/*/junos";

    n ns xnm = "http://xml.juniper.net/xnm/1.1/xnm";

    n ns jcs = "http://xml.juniper.net/junos/commit-scripts/1.0";

    TIP It is easiest to just copy and paste these namespaces into each new scriptas part of the boilerplate rather than trying to type them out by hand.

    import : The import statement is used to import code from one script intothe current script. As the junos.xsl script contains useful default tem-plates and parameters, all scripts should import this le. The import "../import/junos.xsl"; line from the boilerplate is all a script needs toaccomplish this.

    match conguration: This code block is the main template of the commitscript.

    As discussed in the previous section, there are two signicant differences

    between the boilerplates used for op and event scripts and the boilerplateused for commit scripts. Both of these differences exist to simplifycommit scripts and are discussed in this and subsequent sections.

    The rst difference between the boilerplates is that op and event scriptsstart with a match / main template, while commit scripts begin theirprocessing in a match configuration main template.

    The match configuration template is used by commit scripts because itsimplies the retrieval of XML data from the post-inheritance candidateconguration provided to commit scripts in their source tree within a

  • 8/13/2019 Applying Junos Configuration Automation

    14/102

    12 Day One: Applying Junos Con guration Automation

    top-level element named . This simplicationallows conguration information to be retrieved by referencing itstarting with its top-level conguration hierarchy. For example, thesystem host-name can be retrieved with the following code:

    var $configured-host-name = system/host-name;

    NOTE The source tree was discussed in volume two of this series, Day One:Applying Junos Event Automation . For event scripts, the source treeconsists of a top-level element named . Locationpaths in event scripts that refer to this element must include the entirepath:

    var $process-name = event-script-input/trigger-event/process/name;

    Contained within the source tree element is achild element named that holds the entire post-inheri-tance candidate conguration. If commit scripts used a match / template like op and event scripts do, then it would be necessary toinclude the full source tree path to the desired conguration data:

    var $location = commit-script-input/configuration/snmp/location;

    Commit scripts routinely make extensive queries into the congurationdata, and requiring the full path to be specied would be tedious forscript writers. The solution was to create a separate match / template

    within the junos.xsl le:

    The above code from the junos.xsl import le is written in XSLT, buthere is the corresponding SLAX code:

    match / { { apply-templates commit-script-input/configuration; }}

    Because all scripts import the junos.xsl le, this default templatebecomes part of every commit scripts code.

    NOTE Op and event scripts observe no ill effect from the inclusion of a match/ template in the junos.xsl le because their local match / templateoverrides the imported template.

  • 8/13/2019 Applying Junos Configuration Automation

    15/102

    Chapter 1: Introducing Commit Scripts

    When a script rst begins, Junos searches the code for a template thatmatches the current source tree node. The rst node checked is the rootnode, which matches the match / template causing Junos to beginexecuting the code found within that template.

    If a specic node is desired then this process can be repeated by usingthe apply-templates statement, which causes the script engine to searchfor a template that matches the provided location path. In the statementshown above, apply-templates commit-script-input/configuration isinstructing Junos to nd a template that matches the node, namely, the match configuration template that begins commitscript operation.

    MORE? For more information on unnamed match templates (for example, matchconfiguration ) see the Conguration and Diagnostic Automation manual of the Junos documentation at www.juniper.net/techpubs/.

    Whichever node matches the templates match statement becomes thedefault context node within that template. All location paths start witha reference point of that default context node, unless they are based on anode-set variable, are based on a function result, or appear withinfor-each loops.

    NOTE In the case of event scripts, using a match / main template causes the

    context node to be the root node, so all location paths use the full pathto the desired information:

    var $process-name = event-script-input/trigger-event/process/name;

    Because commit scripts start with a context node of ,their location paths can begin with the relevant top-level congurationhierarchy:var $location = snmp/location;

    This is equivalent to the following root-based path into the Junoscandidate conguration:/commit-script-input/configuration/snmp/location

    Post-inheritance Con guration

    As mentioned previously, the candidate conguration provided tocommit scripts within the source-tree element isthe post-inheritance view. This has two implications:

  • 8/13/2019 Applying Junos Configuration Automation

    16/102

    14 Day One: Applying Junos Con guration Automation

    n The conguration groups inherit into the conguration hierar-chies, and the [edit groups] hierarchy is not included in thepost-inheritance conguration.

    n No inactive statements are present in the post-inheritanceconguration.

    Typically this is the behavior a commit script expects because it isonly concerned with the actual conguration that will be committedonto the device. But some commit scripts need to verify the [editgroups] hierarchy and/or view the inactive statements present in theconguration. In those scenarios, the non-inherited candidateconguration must be requested through the API element:var $configuration = jcs:invoke( "get-configuration" );

    The resulting variable can then be parsed to pull out whateverconguration data is required:var $re0-group = $configuration/groups[name == "re0"];

    ALERT! Do not use the API element within a commitscript prior to the following releases: 9.3S5, 9.4R4, 9.5R3, 9.6R2, or10.0R1, as it can cause the Junos device to hang while booting. Forfurther details refer to PR 452398.

    junos:changed

    The post-inheritance conguration provided to commit scriptsindicates what changes are present in the candidate conguration byincluding the junos:changed attribute, with a value of "changed" , onall changed nodes as well as on their parent and ancestor nodes.

    { "juniper1"; { { "admin"; "2001"; "superuser"; { "$1$usVGUcj1$JA/9xEqNrFDImo02nP9tN."; } }

  • 8/13/2019 Applying Junos Configuration Automation

    17/102

    Chapter 1: Introducing Commit Scripts

    } {

    ; } { { "messages"; { "any"; ; } } }}

    The above example shows the post-inheritance conguration of acommit script in which the devices hostname has been changed. Thejunos:changed attribute on both the element as well as onits parent element indicates this change.

    ALERT! When a Junos daemon generates a commit warning, it does not removethe junos:changed attributes from the changed elements, and theypersist through following commits. This makes the attribute unreliableas an indication of new changes because it actually reects changes thatoccurred since the last daemon-warning-free commit, rather thanchanges that occurred since the last commit. (Commit script messages, discussed in Chapter 2, do not cause the sameimpact to the junos:changed attribute that Junos daemon warningmessages do).

    junos:group

    Conguration groups are used as repositories of common congura-tion statements that inherit into multiple conguration hierarchies.Although the group hierarchy is not present in the post-inheritanceconguration provided to commit scripts, it is possible to determine theeffect that groups had on the conguration by looking for the

    junos:group attribute. This attribute is included on every congurationelement that originated from a conguration group. The value of thejunos:group attribute is the conguration group name it was inheritedfrom. { { "public"; "read-only";

  • 8/13/2019 Applying Junos Configuration Automation

    18/102

    16 Day One: Applying Junos Con guration Automation

    }}

    In this example, the entire [edit snmp] hierarchy has been inheritedfrom the re0 conguration group, as reected by the presence of thejunos:group attribute in every conguration element with a value of"re0" .

    In addition to using a different match template, the commit scriptboilerplate also differs from op and event scripts because it does notinclude a result tree top-level element. Op scripts have , and event scripts have , so whydoesnt the commit script boilerplate include a element?

    The answer is that this results element is not necessary within theboilerplate because the match / template in the junos.xsl import leautomatically writes it to the result tree. The template was shownearlier in this chapter:

    match / { { apply-templates commit-script-input/configuration;

    }}Commit script execution begins with this template, causing the element to always be written as the top-levelelement of the result tree. The match configuration boilerplatetemplate is called through the apply-templates statement, and allelements written to the result tree by the commit script are enclosedcorrectly within .

    As an example, two common result tree elements used by commitscripts are and (both are discussed inChapter 2), and a commit script that has the following match configu-

    ration template:match configuration { { "This is a warning message."; } { "This is an error message."; }

  • 8/13/2019 Applying Junos Configuration Automation

    19/102

    Chapter 1: Introducing Commit Scripts

    }Creates this result tree:

    { { "This is a warning message."; } { "This is an error message."; }

    }

    Result Tree Interaction

    All script types can create a result tree, but commit scripts make moreextensive use of this communication path to Junos than either op orevent scripts. Op and event scripts only use the result tree to displayoutput. Most communication between Junos and op and event scriptsoccurs through functions, not through the result tree.

    However, the inclusion of commit scripts within the commit processmakes their result tree output extremely important. The result treeprovides the instructions for Junos to change the conguration, todisplay warning messages, to log syslog messages, or to cancel thecommit with an error. While commit scripts can use the same func-tions and can interact with the Junos API in the same manner as op andevent scripts, this use is not common. The typical commit scriptperforms its processing by using only the post-inheritance candidateconguration as input and writing its instructions for Junos to theresult tree.

    Boot-up Commit

    As a Junos devices boots, it must perform a commit to initialize itsdaemons with the stored conguration. As this is a special commit, youshould consider how any new commit scripts work during this process.

    This boot-up commit follows the same pattern as the standard commitprocess, including the execution of congured commit scripts. Thereare two important implications of the boot-up commit:

    n Some information, such as chassis components, is not available dur-ing the boot-up commit.

  • 8/13/2019 Applying Junos Configuration Automation

    20/102

    18 Day One: Applying Junos Con guration Automation

    n Commit errors during the boot-up commit cause the device to bootwith no conguration.

    To illustrate the above points, consider chassis components. When theconguration is rst committed during the boot-up process the chassiscomponents have not yet been initialized, so any chassis-relatedinformation is not available. If a commit script generates a commiterror due to this lack of information, then the device boots with noconguration. The device remains in this state until an operatormanually resolves the problem.

    Keep this in mind as you read through the following chapters and thinkof ways to use commit scripts within your own network. Part of yourcommit script design process should include consideration of theboot-up commit and how your commit script responds to it.

    Commit Script Checklist

    The following questions are recommended as checks to perform whenadding a new commit script:

    1. Has the script been copied to /var/db/scripts/commit on allrouting-engines?

    2. Has the script been enabled under [edit system scripts commit] on all routing-engines?

    3. If transient changes are used, is allow-transients congured under[edit system scripts commit] ?

    4. If Junos API information requests are performed, does the scriptwork correctly during the boot-up commit?

    5. If Junos API information requests are performed, does the scriptresult in a consistent conguration between the master routing-engine and all other routing-engines? (The other routing-enginesmight not have access to the same information as the master.)

  • 8/13/2019 Applying Junos Configuration Automation

    21/102

    Chapter 2

    Commit Feedback and Control

    20

    23

    25

    27

    29

    Feedback and Control Options 33

    Element and Template Summary 34

  • 8/13/2019 Applying Junos Configuration Automation

    22/102

    20 Day One: Applying Junos Con guration Automation

    Including commit scripts within the commit process provides theability to alter the commit process or to provide feedback to thecommitting user through notications and warnings. Junos op andevent scripts use the result tree element or the jcs:output() function to display output on the console or within their output lerespectively, but commit scripts cannot use these methods to delivermessages to committing users. Instead, commit scripts use one ofthree result tree elements to provide feedback as well as commitcontrol: , , and . This chapterdiscusses these three result tree elements, their relevant child ele-ments, and how to use them.

    As the name implies, the element causes a warningmessage to be displayed to the console of the committing user. Thecommit process is not affected by messages andcompletes successfully unless other errors are found. Here are somepossible uses for messages:

    n Drawing attention to conguration problems that should becorrected.

    n Indicating that the commit script is making an automatic change

    or performing another action that the user should be aware of.n Informing the committing user that the commit script is not

    performing its usual actions due to a problem with the congura-tion, system, or Junos version in use.

    To display a warning message, write the element to theresult tree with a child element of that contains the text todisplay. So using the traditional Hello World! example, the followingcode:match configuration { { "Hello World!"; }}

    ... displays this message as part of the commit process:[edit]jnpr@host1# commitwarning: Hello World!commit complete

  • 8/13/2019 Applying Junos Configuration Automation

    23/102

    Chapter 2: Commit Feedback and Control

    Warn If fxp0 Isnt Inherited

    A more useful example would be to provide a when thefxp0 interface is not being inherited from the re0 or re1 congurationgroup. Fxp0 is the out-of-band management interface for many Junosdevices. The re0 and re1 conguration groups have a unique character-istic in that they are inherited only by the indicated routing engine. So,if a conguration is being committed on routing-engine 0, it ignores thecontents of conguration group re1, and vice versa.

    The advantage of this behavior is that it allows routing-engine specicconguration to be included within a conguration le that is sharedbetween both routing-engines.

    MORE? For more information on the re0 and re1 conguration groups see theCLI User Guide within the Junos documentation at www.juniper.net/ techpubs/.

    One routing-engine specic item that is commonly included within there0 and re1 groups is the interface fxp0 conguration. The commitscript example below tests if the fxp0 interface is present, and if theinterface is present, the script displays a warning message if the congu-ration is not inherited from either the re0 or re1 conguration group.

    /* check-fxp0-inheritance.slax */version 1.0;

    ns junos = "http://xml.juniper.net/junos/*/junos";ns xnm = "http://xml.juniper.net/xnm/1.1/xnm";ns jcs = "http://xml.juniper.net/junos/commit-scripts/1.0";

    import "../import/junos.xsl";

    match configuration {

    var $fxp0-interface = interfaces/interface[name == "fxp0"];

    /* If fxp0 is configured, but not inherited from re group, then display warning */ if( $fxp0-interface &&

    jcs:empty( $fxp0-interface[@junos:group=="re0" || @junos:group=="re1"] ) ) { { "fxp0 configuration is present but not inherited from re group"; } }

    }

  • 8/13/2019 Applying Junos Configuration Automation

    24/102

    22 Day One: Applying Junos Con guration Automation

    Chapter 1 revealed that the post-inheritance candidate congurationprovided to commit scripts indicates group inheritance through thejunos:group attribute. Every conguration element that originates in agroup has that groups name tagged to the element as the value of itsjunos:group attribute.

    The above commit script takes advantage of this behavior by searchingfor a junos:group attribute on the fxp0 interface node with a name ofeither re0 or re1. If the fxp0 interface is present, but it lacks ajunos:group attribute with one of those values, then the followingmessage is displayed when the conguration is committed:

    [edit]jnpr@host1# commit

    warning: fxp0 configuration is present but not inherited from re groupcommit complete

    Try It Yourself: Host-name Should Inherit from Con guration Group

    Create a commit script that generates a commit warning message if the host-name is not inheritedfrom the re0 or re1 conguration groups.

    Child Elements

    The child element is required for all elements.This text is displayed on the same line as the "warning:" statement.While it is often sufcient for simple warnings to include only a , at times it is helpful to provide additional information throughsome of the optional child elements of . The two mostcommonly used child elements, which are both described in the follow-ing sections, are and . These can be seen intypical daemon warning messages such as the following:

    [edit]jnpr@host1# commit[edit interfaces ge-0/0/1 unit 0 family inet]

    'address 10.0.0.1/24' warning: identical local address is found on different interfacescommit complete

    In this example, the warning message shown is identical local addressis found on different interfaces , but there are additional lines ofinformation displayed as well. The rst line displays the hierarchywhere the problem conguration is located, within brackets, and iscreated by using the element. The second line points out

  • 8/13/2019 Applying Junos Configuration Automation

    25/102

    Chapter 2: Commit Feedback and Control

    the exact conguration statement that caused the warning. It iscreated by using the element and results in a slightlyindented string enclosed in single quotes for emphasis.

    MORE? To learn about additional child elements of see theConguration and Diagnostic Automation Guide within the Junosdocumentation at www.juniper.net/techpubs/.

    As shown in the prior section, the [edit interfaces ge-0/0/1 unit 0family inet] output line is an example of output.

    This element makes the problem hierarchy stand out and is mostuseful when there are multiple locations within the conguration thatcould be the source of the warning. Problems with interface congu-ration, as demonstrated above, are examples of where the element can be helpful.

    The following script displays a warning message when any login classhas been assigned the all permission bit. It uses the element to display the hierarchy of the problem login class:

    /* check-permissions.slax */version 1.0;

    ns junos = "http://xml.juniper.net/junos/*/junos";ns xnm = "http://xml.juniper.net/xnm/1.1/xnm";ns jcs = "http://xml.juniper.net/junos/commit-scripts/1.0";

    import "../import/junos.xsl";

    match configuration { /* Warn about any login classes with the all permission bit */ for-each( system/login/class[ permissions == "all" ] ) { { "[edit system login class " _ name _ "]"; "Permission all is assigned to invalid class."; } }}

    With this script enabled, assigning any login class the all permissionbit results in the following warning message:

    [edit]jnpr@host1# commit[edit system login class sandbox] warning: Permission all is assigned to invalid class.commit complete

  • 8/13/2019 Applying Junos Configuration Automation

    26/102

    24 Day One: Applying Junos Con guration Automation

    jcs:edit-path

    The check-permissions.slax script results in both an and line being displayed within the warning message. But the string was built manually by the script, which can betedious for deep hierarchies. A more efcient method of including an element is to call the jcs:edit-path template and allow it toautomatically generate the element.

    One of the default templates included within junos.xsl is jcs:edit-path ,which is usable in any commit script. The template works by buildingthe hierarchy of the context node recursively and including the resultstring within an element. This makes it ideal to use within

    a for-each loop where each iteration through the loop alters the contextnode. If the path that should be displayed by is the same asthe for-each loops context node then jcs:edit-path can determine thepath by default, but if the context node does not reect the path thatshould be included then the $dot parameter of jcs:edit-path can be setto the desired node.

    The following script shows how jcs:edit-path can simplify the addi-tion of an to a element. This script isdesigned to provide a warning message about any logical interface thatdoes not have a description congured:

    /* check-descriptions.slax */version 1.0;

    ns junos = "http://xml.juniper.net/junos/*/junos";ns xnm = "http://xml.juniper.net/xnm/1.1/xnm";ns jcs = "http://xml.juniper.net/junos/commit-scripts/1.0";

    import "../import/junos.xsl";

    match configuration {

    /* Loop through all logical interfaces */ for-each( interfaces/interface/unit ) {

    /* Missing description */ if( jcs:empty( description ) ) { { call jcs:edit-path(); "Interface description is missing."; } } }}

  • 8/13/2019 Applying Junos Configuration Automation

    27/102

    Chapter 2: Commit Feedback and Control

    The check-descriptions.slax script results in warning messages similarto this when the interface descriptions are missing:

    [edit]jnpr@host1# commit[edit interfaces interface ge-0/0/3 unit 0] warning: Interface description is missing.[edit interfaces interface ge-0/1/0 unit 0] warning: Interface description is missing.commit complete

    Using the jcs:edit-path template causes the full hierarchy of thecontext node to be displayed above the warning message. This makesit clear to the user exactly what interface and unit needs to be cor-rected to remove the warning.

    Try It Yourself: ISIS Interface Lacks Family Iso

    Create a warning message for every interface enabled for the ISIS protocol that does not havefamily iso congured. Include an to better document the problem.

    The element indicates the exact conguration statementthat caused the warning. Returning to the daemon warning messageshown earlier in the chapter, the ' address 10.0.0.1/24' line is thestatement of the warning message:

    [edit]jnpr@host1# commit[edit interfaces ge-0/0/1 unit 0 family inet] 'address 10.0.0.1/24' warning: identical local address is found on different interfacescommit complete

    The statement can be specied manually, similar to the element, by including the element with its appropriatevalue within the element. In addition, thejcs:statement template can be called to automatically generate a element based on the context node, or the templates $dot parameter can be set to select a different node.

    This example script provides a warning for event scripts that arereferenced within an event policy, but are not enabled within theconguration. It includes both an and a within its elements:

    /* check-event-scripts.slax */

  • 8/13/2019 Applying Junos Configuration Automation

    28/102

    26 Day One: Applying Junos Con guration Automation

    version 1.0;

    ns junos = "http://xml.juniper.net/junos/*/junos";ns xnm = "http://xml.juniper.net/xnm/1.1/xnm";ns jcs = "http://xml.juniper.net/junos/commit-scripts/1.0";

    import "../import/junos.xsl";

    match configuration {

    /* Save these hierarchy nodes */ var $event-options = event-options; var $system = system;

    /* Look for any referenced event scripts */ for-each( event-options/policy/then/event-script ) {

    /* Record event-script name */ var $name = name;

    /* Check if enabled in either location */ var $under-event-options = $event-options/event-script/file[name == $name]; var $under-system-scripts = $system/scripts/op/file[name == $name];

    /* If it isn't enabled in either location then log an warning */ if( jcs:empty( $under-event-options ) and jcs:empty( $under-system-scripts ) ) { { call jcs:edit-path( $dot = ancestor::policy ); call jcs:statement(); "Event script is not enabled.";

    } } }}

    This script uses the jcs:edit-path and jcs:statement templates to easilycreate and elements based on the context nodeor a separate reference node. The should refer to theevent-script conguration statement so the jcs:statement template canuse the context node of the for-each loop. The however,should be set to the event policy that triggers the event script. This isaccomplished by setting the $dot parameter to the grandparent eventpolicy by using the ancestor axis in the location path.

    Here is the full warning message that is displayed when an event script isnot properly enabled. It provides all the information required to identifyexactly what needs to be resolved:

    [edit]jnpr@host1# commit[edit event-options policy save-core-files]

  • 8/13/2019 Applying Junos Configuration Automation

    29/102

    Chapter 2: Commit Feedback and Control

    'event-script save-core-files.slax;' warning: Event script is not enabled.

    commit complete

    While the element writes a warning message to theconsole of the committing user, the element can be used togenerate more permanent warnings by writing them to the syslog.

    The element has a single child element thatcontains the actual text to be logged to the syslog. All syslog messagesgenerated by this element are sent from the daemon facility with asevere warning.

    NOTE No syslog message is generated by the element in the follow-ing two circumstances:

    n When a commit check is being performed.n During the initial boot-up commit.

    The following script demonstrates how to use the element towrite warning messages to the syslog:

    /* check-loopback-filter.slax */version 1.0;

    ns junos = "http://xml.juniper.net/junos/*/junos";ns xnm = "http://xml.juniper.net/xnm/1.1/xnm";ns jcs = "http://xml.juniper.net/junos/commit-scripts/1.0";

    import "../import/junos.xsl";

    match configuration { var $lo0-interface = interfaces/interface[name == "lo0"]; if( jcs:empty( $lo0-interface/unit[name=="0"]/family/inet/filter/input ) ) { { "Warning: no lo0.0 firewall filter is assigned."; } }

    } When no rewall lter is congured for the lo0.0 interface the follow-ing message is sent to the syslog:

    Nov 19 22:02:43 host1 cscript: Warning: no lo0.0 firewall filter is assigned.

  • 8/13/2019 Applying Junos Configuration Automation

    30/102

    28 Day One: Applying Junos Con guration Automation

    Comparison to jcs:syslog()

    The result tree element for commit scripts performs a rolesimilar to the jcs:syslog() function, which is available to all script

    types, in that the element causes its text to be written to thesyslog. One difference between the two approaches, though, is thatunlike the jcs:syslog() function, the result tree element hasno control over its facility and severity; it always logs messages fromthe daemon facility at warning severity. In other words, the message: "This is a syslog message";Is equivalent to:expr jcs:syslog( "daemon.warning", "This is a syslog message" );

    Other differences are a result of when the instruction is processed by Junos. The jcs:syslog() function logs the message to the syslogimmediately, while the script is still executing, but the elementis only evaluated when the commit script result trees are examined bythe Junos management daemon following the completion of all commitscripts. This has two implications:

    1. Syslog messages from are only logged if the commitprocess is successfully completed. A element in theresult tree causes the syslog message to not be logged. The jcs:syslog() function is always logged, whether the commitresults in an error or not.

    2. Syslog messages from jcs:syslog() are logged before messagesfrom . This affects their order within the syslog messagele even if the elements occur earlier in the commit scriptthan the jcs:syslog() function.

    Other differences exist, all of which are shown inTable 2.1:

    Table 2 .1 Comparison of and jcs:syslog()

    jcs:syslog()

    Supported script types Commit scripts Commit, Op, and Eventscripts

    Facility / Severity Daemon / warning Configurable

    Commit halted by

    Message is not logged Message is logged

  • 8/13/2019 Applying Junos Configuration Automation

    31/102

    Chapter 2: Commit Feedback and Control

    commit check" performed Message is not logged Message is logged

    When loggedAfter all commit scriptsfinish processing

    During commit scriptprocessing

    Boot up commit Message is not logged Message is not logged

    Try it Yourself: Compare Syslog Methods

    Create a commit script that logs two syslog messages, one using and the other usingjcs:syslog() . Compare the syslog results when a commit is performed versus a commit check .

    So far this chapter has explored how to provide feedback from thecommit process in the form of warning messages displayed on theconsole or sent to the syslog. But in addition to giving feedback,commit scripts can take control of the commit process itself. If a scriptnds a fatal aw within the candidate conguration the script can haltthe commit process, preventing application of the undesired congura-tion. This control is achieved by using the result treeelement.

    The element is used in the same way as andhas identical child elements. Like the element requires a child element that contains the text todisplay to the committing user. But unlike a message, a message halts the commit process. Warning messagesremind users to x small aws or draw attention to parts of the con-guration that need to be added. If the conguration should never bepermitted to commit in its current form, errors are used. This situationcould occur because of catastrophic conguration lapses, such as acompletely missing hierarchy, or as the result of more subtle problemsthat violate an organizations policies.

    Basic Sanity Checking

    The simplest use for is to do basic sanity checking. Asmentioned in the last section, this might consist of ensuring that certainhierarchies are always present, such as the [edit interfaces] or [editprotocols] hierarchy. Or it might dig deeper, requiring that a re0 and

  • 8/13/2019 Applying Junos Configuration Automation

    32/102

    30 Day One: Applying Junos Con guration Automation

    re1 conguration group be congured, or that ospf is enabled on allcore interfaces.

    Consider the following example that requires that the SSH service isenabled, that the 'jnpr' account is congured, and that the fxp0interface has been assigned an IP address:

    /* basic-sanity-check.slax */version 1.0;

    ns junos = "http://xml.juniper.net/junos/*/junos";ns xnm = "http://xml.juniper.net/xnm/1.1/xnm";ns jcs = "http://xml.juniper.net/junos/commit-scripts/1.0";

    import "../import/junos.xsl";

    match configuration {

    /* Ensure that ssh is enabled */ if( jcs:empty( system/services/ssh ) ) { { "SSH must be enabled."; } }

    /* Ensure that user account jnpr exists */ if( jcs:empty( system/login/user[name == "jnpr"] ) ) { { "The jnpr user account must be created."; } }

    /* Verify that fxp0 has an IP address */ var $fxp0-interface = interfaces/interface[name == "fxp0"]; if( jcs:empty( $fxp0-interface/unit[name=="0"]/family/inet/address/name ) ) { { "fxp0 must have an IP address."; } }}

    In the basic-sanity-check.slax script, three separate tests are performedand a element is written to the result tree if any elementsfail. A single element is sufcient to halt the commit, butin the worst case scenario all three errors could occur:

    [edit]jnpr@host1# commiterror: SSH must be enabled.error: The jnpr user account must be created.error: fxp0 must have an IP address.error: 3 errors reported by com mit scriptserror: commit script failure

  • 8/13/2019 Applying Junos Configuration Automation

    33/102

    Chapter 2: Commit Feedback and Control

    Try it Yourself: Sanity Checking

    Write a commit script that generates a if the [edit system] , [edit interfaces] , or[edit protocols] hierarchies are missing.

    and

    All child elements supported by are supported by as well, including the and elements. Also, the jcs:edit-path and jcs:statement templates can beused in an identical manner to the element.

    The following script demonstrates the use of the jcs:edit-path tem-

    plate with a message. It checks for any EBGP peers that donot have a congured prex-limit and requires they be xed before thecommit can succeed:

    /* check-ebgp-peers.slax */version 1.0;

    ns junos = "http://xml.juniper.net/junos/*/junos";ns xnm = "http://xml.juniper.net/xnm/1.1/xnm";ns jcs = "http://xml.juniper.net/junos/commit-scripts/1.0";

    import "../import/junos.xsl";

    match configuration {

    /* Retrieve AS Number */ var $asn = routing-options/autonomous-system/as-number;

    /* Scroll through all EBGP peers */ for-each( protocols/bgp/group[ peer-as != $asn ]/neighbor ) {

    if( jcs:empty( family/inet/unicast/prefix-limit/maximum ) && jcs:empty( ../family/inet/unicast/prefix-limit/maximum ) ) { { call jcs:edit-path(); "EBGP peer must have prefix limit defined."; } } }}

    The check-ebgp-peers.slax script assumes that the peer-as is dened atthe BGP group rather than at the neighbor level, and that an autono-mous-system has been dened within [edit routing-options] . (Thesetwo assumptions could also have been veried by the commit script

  • 8/13/2019 Applying Junos Configuration Automation

    34/102

    32 Day One: Applying Junos Con guration Automation

    itself). The script veries that all EBGP peers have a prex-limit

    dened at either the neighbor or group level. If any peers lack the limitthe script displays an error message including the display-ing the neighbor hierarchy, and halts the commit:

    [edit]jnpr@host1# commit[edit protocols bgp group AS65535 neighbor 10.0.0.2] EBGP peer must have prefix limit defined.error: 1 error reported by commit scriptserror: commit script failure

    Try it Yourself: Incorrect Autonomous-system Number

    Write a commit script that generates a if the autonomous-system number is not setto 65000 . Include and elements to better document the problem.

    Errors Based on Chassis Components

    Commit scripts have access to the same Junos API elements as op andevent scripts, which means that they can be programmed to generate messages based on the conguration as well as on otherfactors such as what PICs are installed, etc.

    But perform such programming with caution. Information from theAPI is not always available and commit scripts need to be pro-grammed to handle this possible problem correctly. For example,during the boot-up commit many API elements do not return data, asthe relevant daemons have not yet initialized. Also remember thatcommit scripts run on all routing-engines of the system, and manytimes only the master routing-engine has access to all the informationavailable from the API. This makes it very possible for a commitscript that requests API information and is running on one routing-engine to reach a different decision than the same commit scriptrunning on another routing-engine, which can lead to inconsistencyacross the routing-engines. In addition, PICs are added, FPCs areremoved, and other changes occur, all outside of the commit process.Event scripts can be used to watch for these changes, but rememberthat commit scripts do not see the changes until the next commit isrequested.

    Based on the above risks, it is usually best to have commit scriptsavoid using information from Junos API elements when making theirconguration control decisions.

  • 8/13/2019 Applying Junos Configuration Automation

    35/102

    Chapter 2: Commit Feedback and Control

    Feedback and Control Options

    This chapter has presented numerous examples of commit scripts thatprovide feedback or control the conguration through the , , and result tree elements. Table2.2 shows a list of the different example conditions and actions taken:

    Table 2 .2 Examples from this chapter

    Condition Action

    Fxp0 isnt inherited message

    'all' permission bit assigned to class message

    Missing interface description messageEvent script is not enabled message

    Loopback rewall lter is missing message

    SSH is not enabled message and halt commit

    'jnpr' user account is missing message and halt commit

    Fxp0 does not have an IPv4 address message and halt commit

    EBGP peer lacks pre x-limit message and halt commit

    Consider the examples that were used, the conditions that werechecked, and the resulting actions. Is it worthwhile for a commit scriptto look for these conditions? Do the actions seem appropriate? Theanswer to these questions varies for each network because all networkadministrators have different opinions about what should and shouldnot be present within their conguration. Individual administratorswill all make different decisions on which conditions are problematicenough for warning messages and which conguration aws shouldresult in commit errors.

    This is what makes Junos commit scripts so useful they allowadministrators from each network to decide for themselves what warn-

    ings are delivered and what conguration problems might causecommit errors. Commit scripts provide the tools necessary to auto-mate the commit process to run in a way that works best for eachindividual network.

    Try it Yourself: Brainstorm Warnings and Errors

    Write a list of conguration problems that would be of interest for your network. Note if theyshould result in a , , or .

  • 8/13/2019 Applying Junos Configuration Automation

    36/102

    34 Day One: Applying Junos Con guration Automation

    BEST PRACTICE Creating feedback and control options is an ongoing process. Manyconguration violations are readily apparent, but other problems mightonly be realized after a human error has resulted in a disruption. Whencorrecting conguration errors, always consider if the addition of newcommit script checks could prevent the issue from occurring again.

    Element and Template Summary

    Table 2.3 and 2.4 summarize the conguration feedback and controlresult tree elements and templates.

    Table 2 .3 Feedback and Control Result Tree Elements

    Result Tree Elements Child Elements

    - Display warningmessage to console

    - [Required] The text to display

    - Relevant conguration hierarchy of thewarning message

    - Conguration statement that is thecause of the warning message

    - Writes a message to thesyslog from the daemon facility witha severity of warning

    - [Required] The text to write to thesyslog

    - Display error messageto console and halt commit process

    - [Required] The text to display

    - Relevant conguration hierarchy of theerror

    - Conguration statement that is thecause of the error

    Table 2.4 Feedback and Control Templates

    Templates Template Parameters

    jcs:edit-path - Generates an element automaticallyfor the context node

    $dot - Generate for selected node ratherthan context node

    jcs:statement - Generates a element automatically for thecontext node

    $dot - Generate for selected node ratherthan context node

  • 8/13/2019 Applying Junos Configuration Automation

    37/102

  • 8/13/2019 Applying Junos Configuration Automation

    38/102

    36 Day One: Applying Junos Con guration Automation

    Chapter 2 demonstrated the use of , , and to provide conguration feedback and control. Thosetechniques can be used to bring problems to the attention of thecommitting user, who can then resolve them manually.

    But many conguration issues do not require manual intervention. Theability to automate conguration changes is a powerful capability ofcommit scripts. This means that instead of asking the user to x anissue, the script simply resolves the problem automatically, ensuringthat the conguration is structured according to the networks policiesand desires.

    Adding/Editing/Replacing

    Conguration changes are made by adding a element to theresult tree. The element encloses the conguration hierarchyand the statement that should be changed: { { "host2"; }}

    Notice that the full hierarchy is enclosed, starting at the top-level. The

    conguration modeload

    command is used the same way, by includingthe full hierarchy of the desired change. In the elementabove, if host-name is present in the conguration then it is changed to"host2" , otherwise host-name is added to the conguration with"host2" as its value.

    MORE? To learn more about the load conguration mode command see theCLI User Guide within the Junos documentation at www.juniper.net/ techpubs/.

    As shown in Figure 1.1, conguration changes affect the candidateconguration. This is the same conguration that the user has editedand requested to be committed. After the commit process is complet-ed, all changes performed by commit scripts are included within thecommitted conguration, just as if they had been done manually by auser.

    The fact that elements impact the candidate conguration ismade explicit by using the commit check command. This performs acommit to check for errors, but does not actually apply the committed

  • 8/13/2019 Applying Junos Configuration Automation

    39/102

    Chapter 3: Changing the Con guration

    conguration. Yet the elements are still applied to thecandidate conguration. For example, when the above element is loaded into a commit script and a commit check is per-formed, the following effect is seen:[edit]jnpr@host1# show system host-namehost-name host1;

    [edit]jnpr@host1# commit checkconfiguration check succeeds

    [edit]jnpr@host1# show system host-name

    host-name host2;

    Notice after the commit check is performed that the host-name withinthe conguration is now set to host2 , yet the prompt still says host1 .This is because the committed conguration has not changed, only thecandidate conguration has changed. In the normal commit processthis difference is unnoticed because a successful commit results in thecandidate conguration becoming the committed conguration, butbecause commit check does not follow the complete commit process itallows the effects of elements to be clearly shown.

    Try it Yourself: Commit Check and the Element

    Write a simple commit script that changes a single conguration setting. Perform a commitcheck and verify that the candidate conguration is altered, but that the committed congura-tion remains unchanged. Perform a normal commit and verify that the change is now visible inthe committed conguration.

    Automatically Add Missing Con guration

    The past chapter included an example script called basic-sanity-check.slax that checked for the following three conditions and halted thecommit with an error if they were missing:

    n SSH service is enabledn "jnpr" user account is presentn Fxp0 interface has an IPv4 address

  • 8/13/2019 Applying Junos Configuration Automation

    40/102

    38 Day One: Applying Junos Con guration Automation

    Providing an error message and asking the user to x the problems is avalid strategy, but if the missing conguration is standardized then whynot have the commit script x the problem automatically? It might notbe possible to generate the fxp0 interface automatically, because theaddress is different for every device. Still, enabling SSH and adding the"jnpr" user account should be standardized, and this action could beperformed by the commit script instead of requiring manual interven-tion.

    The following commit script modies the basic-sanity-check.slax scriptand automatically xes the standardized portions:

    /* basic-sanity-check-and-fix.slax */

    version 1.0;

    ns junos = "http://xml.juniper.net/junos/*/junos";ns xnm = "http://xml.juniper.net/xnm/1.1/xnm";ns jcs = "http://xml.juniper.net/junos/commit-scripts/1.0";

    import "../import/junos.xsl";

    match configuration {

    /* Ensure that ssh is enabled - if not then enable it */ if( jcs:empty( system/services/ssh ) ) { {

    { { ; } } } { "Enabling ssh"; } }

    /* Ensure that user account jnpr exists - if not then add it */ if( jcs:empty( system/login/user[name == "jnpr"] ) ) { { { { { "jnpr"; "super-user"; { "$1$RHL6So3y$kcOy3vb6YiWf6FAJzHi7j1";

  • 8/13/2019 Applying Junos Configuration Automation

    41/102

    Chapter 3: Changing the Con guration

    }

    } } } } { "Adding jnpr user account"; } }

    /* Verify that fxp0 has an IP address */ var $fxp0-interface = interfaces/interface[name == "fxp0"]; if( jcs:empty( $fxp0-interface/unit[name=="0"]/family/inet/address/name ) ) { { "fxp0 must have an IP address."; } }}

    The modied script still checks for the same problems, but now whenSSH is not enabled or the jnpr account is missing it adds a element to the result tree and xes the problem automatically. The element has been changed to a element tonotify the committing user that the script made automated congura-tion changes.

    BEST PRACTICE Include a element when making automated changes tonotify the user that the script has changed the conguration.

    The check of the fxp0 interface remains the same as the original script.If no IPv4 address is congured then a element is gener-ated, which halts the commit and requires manual intervention. Itwould be possible to hardcode the needed address into the script andx the problem automatically, but that would result in a separate scriptper each Junos device. Alternatively, if the fxp0 address is assigned in adeterministic fashion based on some value that the script can access(such as the host-name), then it would be possible for the script togenerate it automatically. In the case of the script above, that condi-tion still remains an error and requires the users attention to x.

    Try it Yourself: Automated Con guration Fixes

    Identify a standard part of your conguration that should always be present. Write a commitscript that automatically adds it when missing and generates a message informingthe user of the change.

  • 8/13/2019 Applying Junos Configuration Automation

    42/102

    40 Day One: Applying Junos Con guration Automation

    Replacing Con guration

    Using the element is equivalent to using the load replace conguration command. By default, conguration content is mergedinto the conguration, new items are added, and conicting statementsare overridden. But as with the load replace conguration modecommand, it is possible to indicate that the enclosed congurationshould replace the existing conguration, rather than simply merginginto it. This is done by adding the replace attribute to the desiredconguration element with a value of "replace" .

    MORE? To learn more about the load replace conguration mode commandsee the CLI User Guide within the Junos documentation at www.juniper.net/techpubs/.

    Consider the case of a Junos device that should always have its syslogmessages le congured in the following manner:file messages { any notice;}

    No other facilities should be congured and no other syslog optionsshould be included. If a commit script is congured to enforce thisconguration by checking for incorrect conguration statements under

    the messages le and issuing a element, without using thereplace="replace" attribute, then the desired result is not achieved.

    Here is the initial faulty commit script:/* faulty-check-syslog-messages.slax */version 1.0;

    ns junos = "http://xml.juniper.net/junos/*/junos";ns xnm = "http://xml.juniper.net/xnm/1.1/xnm";ns jcs = "http://xml.juniper.net/junos/commit-scripts/1.0";

    import "../import/junos.xsl";

    match configuration {

    var $messages-file = system/syslog/file[name == "messages"]; if( jcs:empty( $messages-file ) || count( $messages-file/* ) > 2 || jcs:empty( $messages-file/contents[ name == "any" ]/notice ) ) {

    { {

  • 8/13/2019 Applying Junos Configuration Automation

    43/102

    Chapter 3: Changing the Con guration

    { {

    "messages"; { "any"; ; } } } } } { "Syslog messages file configuration corrected"; } }}

    The script correctly catches an improperly congured messages le,but it does not change the conguration correctly. With the followingconguration pre-commit:file messages { any any; daemon verbose;}

    The conguration is changed to the following by the commit script:file messages { any notice; daemon verbose;}

    The any facility is correctly changed to use the notice severity, but thedaemon facility is not removed. This is because the change was mergedinto the existing conguration; it did not replace it. So any existingconguration statements that were not overridden by merged state-ments remain.

    In order to replace the existing le messages hierarchy, the replace attribute is added with a value of "replace" . Here is the correctcommit script:

    /* check-syslog-messages.slax */version 1.0;

    ns junos = "http://xml.juniper.net/junos/*/junos";ns xnm = "http://xml.juniper.net/xnm/1.1/xnm";ns jcs = "http://xml.juniper.net/junos/commit-scripts/1.0";

  • 8/13/2019 Applying Junos Configuration Automation

    44/102

    42 Day One: Applying Junos Con guration Automation

    import "../import/junos.xsl";

    match configuration {

    var $messages-file = system/syslog/file[name == "messages"]; if( jcs:empty( $messages-file ) || count( $messages-file/* ) > 2 || jcs:empty( $messages-file/contents[ name == "any" ]/notice ) ) {

    { { { { "messages"; { "any"; ; } } } } } { "Syslog messages file configuration corrected"; } }}

    Placing the replace attribute on a conguration element causes thatelement and all its descendents to be replaced within the congurationby the new conguration. If the messages le conguration is thefollowing prior to the commit:file messages { any any; daemon verbose;}

    It becomes the following after the commit script has replaced theexisting le messages hierarchy:

    file messages { any notice;}

    Try it Yourself: Replacing Con guration Hierarchies

    Create a commit script that enforces the requirement that the ospf conguration should consistsolely of an assignment of all interfaces into area 0.

  • 8/13/2019 Applying Junos Configuration Automation

    45/102

  • 8/13/2019 Applying Junos Configuration Automation

    46/102

    44 Day One: Applying Junos Con guration Automation

    /* add-loopback-filter.slax */version 1.0;

    ns junos = "http://xml.juniper.net/junos/*/junos";ns xnm = "http://xml.juniper.net/xnm/1.1/xnm";ns jcs = "http://xml.juniper.net/junos/commit-scripts/1.0";

    import "../import/junos.xsl";

    match configuration {

    var $lo0-interface = interfaces/interface[name=="lo0"]/unit[name=="0"]; if( jcs:empty( $lo0-interface/family/inet/filter/input[filter-name == "in"] ) ) { /* Create the change */ var $change = { { { "in"; } } } call jcs:emit-change( $dot = $lo0-interface/family/inet, $content = $change ); { "Adding lo0 input filter."; } }}

    The add-loopback-lter.slax script assigns an input rewall lter for

    lo0.0 if not already assigned. The code takes advantage of the $dot parameter to minimize the amount of hierarchy that must be includedwithin the conguration change. Because the $dot is set at the familyinet level, the code change can be crafted for that hierarchy and canbegin with a reference to the element. With the $dot param-eter set, and the $content parameter assigned to the congurationchange, the jcs:emit-change template can create the necessary element with the needed conguration hierarchy for thedesired change.

    ALERT! The $dot parameter must refer to an existing node within the congu-

    ration. With the above script, if the lo0 interface is not currentlycongured, or lacks a unit 0 with family inet, then the jcs:emit-change template generates a commit error:

    error: jcs:emit-change called with invalid location (dot)

  • 8/13/2019 Applying Junos Configuration Automation

    47/102

    Chapter 3: Changing the Con guration

    The add-loopback-lter.slax script manually creates a message to indicate that the conguration has been changed, but that isnot necessary when using the jcs:emit-change template. The templatehas a $message parameter that can automatically create a message to display to the committing user. The follow-ing lines of code:

    call jcs:emit-change( $dot = $lo0-interface/family/inet, $content = $change ); { "Adding lo0 input filter.";}Could have been written instead as:

    var $message = "Adding lo0 input filter.";call jcs:emit-change($dot = $lo0-interface/family/inet, $content = $change, $message);

    Try it Yourself: Family MPLS on LDP Interfaces

    Create a commit script that calls the jcs:emit-change template to add family mpls to every inter-face, congured under [edit protocols ldp] , that lacks it.

    Deleting

    At this point, the ability to add, edit, and replace conguration hasbeen demonstrated, but it is also possible to delete congurationstatements as well as complete conguration hierarchies. This action isaccomplished by including the delete attribute on the congurationelement that should be removed inside the element, andsetting the attributes value to "delete" .

    For example, a congured time-zone could be removed by using this element: { {

    ; }}

    The delete attribute can also delete complete conguration hierar-chies. This example removes the [edit protocols ospf traceoptions]conguration hierarchy:

  • 8/13/2019 Applying Junos Configuration Automation

    48/102

    46 Day One: Applying Junos Con guration Automation

    { { { ; } }}

    Conguration hierarchies with identiers can be deleted by includingthe delete attribute on the conguration element and also including itsidentier element as a child element (typically ). This element removes the ge-0/0/0 interface from the conguration. The

    actual conguration element is , but its child element identies the specic interface conguration to remove: { { { "ge-0/0/0"; } }}

    Some conguration statements can have multiple values. To delete asingle value from a multiple-value statement, include the delete

    attribute for the statements conguration element and also include thestatements value. For example, login classes can dene multiplepermission bits. The following element deletes only the "all" permission bit from the "admin" login class: { { { { "admin"; "all"; } }

    }}

    The following example shows the ospf-fxp0-disabled.slax script. Thiscommit script ensures that the fxp0 interface is included under area 0 asa disabled interface and not under any other areas:

    /* ospf-fxp0-disabled.slax */version 1.0;

  • 8/13/2019 Applying Junos Configuration Automation

    49/102

    Chapter 3: Changing the Con guration

    ns junos = "http://xml.juniper.net/junos/*/junos";

    ns xnm = "http://xml.juniper.net/xnm/1.1/xnm";ns jcs = "http://xml.juniper.net/junos/commit-scripts/1.0";

    import "../import/junos.xsl";

    match configuration {

    /* Loop through all ospf areas */ for-each( protocols/ospf/area ) {

    /* Area 0, verify that fxp0 is disabled */ if( name == "0.0.0.0" && jcs:empty( interface[name=="fxp0.0"]/disable ) ) { /* Add the statement since it's missing */ var $content = {

    { "fxp0.0"; ; } } var $message = "Adding fxp0.0 disable"; call jcs:emit-change( $content, $message );

    } /* All other areas, fxp0 not allowed */ else if( name != "0.0.0.0" && interface[name=="fxp0.0"] ){ var $content = { { "fxp0.0"; } } var $message = "Removing fxp0.0"; call jcs:emit-change( $content, $message); } }}

    The commit script loops through all the ospf areas. If the current areais 0.0.0.0 then the script checks if fxp0 is included as a disabledinterface. If it is not present in disabled form, then the jcs:emit-

    change template is used to generate the needed element to addthe desired conguration. No $dot needs to be set because the contextnode is the ospf area and the $content change is designed for thathierarchy level.

    For other areas, the commit script checks if fxp0 is congured, and if itis the script uses jcs:emit-change to create a element thatdeletes it.

  • 8/13/2019 Applying Junos Configuration Automation

    50/102

    48 Day One: Applying Junos Con guration Automation

    Assume the conguration prior to commit is the following:[edit]jnpr@host1# show protocols ospfarea 0.0.0.0 { interface lo0.0; interface ge-0/0/0.0;}area 0.0.0.1 { interface ge-0/0/1.0; interface fxp0.0;}

    The following warning messages are displayed to the committing user:[edit]jnpr@host1# commit[edit protocols ospf area 0.0.0.0] warning: Adding fxp0.0 disable[edit protocols ospf area 0.0.0.1] warning: Removing fxp0.0commit complete

    And the ospf conguration is successfully changed:[edit]jnpr@host1# show protocols ospfarea 0.0.0.0 { interface lo0.0;

    interface ge-0/0/0.0; interface fxp0.0 { disable; }}area 0.0.0.1 { interface ge-0/0/1.0;}

    NOTE As the output example above shows, using the $message parameter ofjcs:emit-change to display a warning message automatically includesan with the context node used as the hierarchy level. This

    is why [edit protocols ospf area 0.0.0.0] and [edit protocolsospf area 0.0.0.1] are included in the output.

    Try it Yourself: Deleting Invalid Name-servers

    Create a commit script for an organization whose name-servers all fall within the 10.0.1.0/24subnet. Delete any congured name-servers from outside that subnet.

  • 8/13/2019 Applying Junos Configuration Automation

    51/102

    Chapter 3: Changing the Con guration

    Activating/Deactivating

    A commit script can activate or deactivate conguration by following asimilar method as deletion. To activate conguration, add the active attribute with a value of "active" . To deactivate conguration, addthe inactive attribute with a value of "inactive" .

    The same approach is used for each type of conguration element withthe delete attribute. For example, to deactivate the [edit snmp] hierarchy, use the following element: { ;}

    Or, to activate the "jnpr" user account, the following element can be used: { { { { "jnpr"; } } }}

    Deactivating

    Deactivating improper conguration is an alternative to generating a and rejecting the entire commit request. Recall thecheck-ebgp-peers.slax script from Chapter 2 that generated an error ifany EBGP peers lacked a prex-limit. The following commit scripttakes a different approach, instead of failing the commit it deactivatesthe problem EBGP peer and generates a warning message. The peer isnot allowed to be active until the prex-limit is put in place, but thisproblem does not prevent other conguration changes from takingeffect.

    /* deactivate-ebgp-peers.slax */version 1.0;

    ns junos = "http://xml.juniper.net/junos/*/junos";ns xnm = "http://xml.juniper.net/xnm/1.1/xnm";ns jcs = "http://xml.juniper.net/junos/commit-scripts/1.0";

  • 8/13/2019 Applying Junos Configuration Automation

    52/102

    50 Day One: Applying Junos Con guration Automation

    import "../import/junos.xsl";

    match configuration {

    /* Retrieve AS Number */ var $asn = routing-options/autonomous-system/as-number;

    /* Scroll through all EBGP peers */ for-each( protocols/bgp/group[ peer-as != $asn ]/neighbor ) {

    if( jcs:empty( family/inet/unicast/prefix-limit/maximum ) && jcs:empty( ../family/inet/unicast/prefix-limit/maximum ) ) { var $content = { { name;

    } } var $message = "EBGP peer is missing prefix limit. Deactivating."; call jcs:emit-change( $dot = .., $content, $message ); } }}

    The EBGP neighbor is deactivated by setting the inactive attribute to"inactive" for the neighbor element and enclosing the identi-er element. The $dot parameter for jcs:emit-change is set to allowthe conguration change to be based on the parent BGP group hierar-

    chy rather than the current context node. A message isprovided to the jcs:emit-change template so the committing user seesa warning similar to the following:[edit]jnpr@jhost1# commit[edit protocols bgp group EBGP neighbor 10.0.0.2] warning: EBGP peer is missing prefix limit. Deactivating.commit complete

    Activating

    Activating conguration is done in the same way as deactivatingconguration, except that the active attribute is added, rather than the inactive attribute, and its value is set to "active" . The difcult partof this process is knowing whether or not the conguration needs to beactivated, because inactive conguration is not present within thepost-inheritance conguration provided to the commit script.

    It is possible to retrieve the conguration, including inactive state-ments, by using the Junos API element, which

  • 8/13/2019 Applying Junos Configuration Automation

    53/102

    Chapter 3: Changing the Con guration

    returns the pre-inheritance candidate conguration by default. Anyinactive elements within this conguration have an inactive attributewith a value of "inactive" .The following shows an example of a commit script that retrieves thecandidate conguration to detect if the autonomous-system is deacti-vated, and if it is inactive the script generates the necessary element to activate it:

    /* activate-asn.slax */version 1.0;

    ns junos = "http://xml.juniper.net/junos/*/junos";ns xnm = "http://xml.juniper.net/xnm/1.1/xnm";ns jcs = "http://xml.juniper.net/junos/commit-scripts/1.0";

    import "../import/junos.xsl";

    match configuration {

    /* Retrieve the current configuration, when doing this be aware of PR 452398 */ var $configuration = jcs:invoke( "get-configuration" );

    if( $configuration/routing-options/autonomous-system[@inactive] ) { { { ; } } { "Activating ASN configuration."; } }}

    ALERT! Do not use the API element within a commitscript prior to the following releases: 9.3S5, 9.4R4, 9.5R3, 9.6R2, or10.0R1, as it can cause the Junos device to hang while booting. Forfurther details refer to PR 452398.

    Reordering

    While the order of most conguration statements is unimportant, someparts of the conguration, such as rewall terms, are processedsequentially and must be in the proper order. Assume that the follow-ing routing-policy has been congured:

  • 8/13/2019 Applying Junos Configuration Automation

    54/102

    52 Day One: Applying Junos Con guration Automation

    policy-statement accept-ospf { term reject {

    then reject; } term ospf { from protocol ospf; then accept; }}

    The intention of the policy is to allow OSPF routes and reject allothers, but the faulty term order causes all routes to be rejected. Tocorrect this the ospf term must be inserted prior to the reject term. Inconguration mode the following command can be used:

    [edit policy-options policy-statement accept-ospf]jnpr@host1# insert term ospf before term reject

    Following this command, the policy now reads:policy-statement accept-ospf { term ospf { from protocol ospf; then accept; } term reject { then reject; }

    }

    Commit scripts are also capable of moving elements before or aftertheir siblings within the conguration. To move congurationhierarchies, such as the different policy terms, use the followingformat:

    { "moving-element-name";}

    The conguration element is referenced by including its unique

    identifying element (typically called name): { "ospf";}

    The insert attribute is used to indicate that an insertion needs to beperformed, and the attribute is set to "before" or "after" to show

  • 8/13/2019 Applying Junos Configuration Automation

    55/102

    Chapter 3: Changing the Con guration

    where it should be placed in reference to the other element. { "ospf";}

    Finally, the reference element is identied by including the identierelement name as an attribute (in the above example, this is "name" )with the reference elements value: { "ospf";}

    The full element to accomplish this is the following: { { { "accept-ospf"; { "ospf"; } } }}

    Reordering among multiple values for a single conguration statement

    differs slightly from the above examples because the various elementshave no identifying child elements, and instead differ only in theirassigned values. In this case, the format used is the following:

    "moving-value";

    Consider the various static-route next-hops: { { { "192.168.1.0/24"; "10.0.0.1";

    "10.0.0.2"; } }}

    To cause the 10.0.0.2 next-hop to be moved in front of the 10.0.0.1next-hop the following code can be used:

  • 8/13/2019 Applying Junos Configuration Automation

    56/102

    54 Day One: Applying Junos Con guration Automation

    { {

    { { "192.168.1.0/24"; "10.0.0.2"; } } }}

    MORE? For more information on reordering conguration elements see the Junoscript API Guide within the Junos documentation at www.juniper.net/techpubs/.

    One common reason to reorder is if a commit script is adding rewallterms, policy terms, or other conguration elements that must then beplaced within their proper order. Unless the entire parent hierarchy isbeing replaced, the new elements are appended to the existing content.In many cases this placement is incorrect and must be xed throughproper reordering. For example, the following script adds a "block-private-ranges" policy to all EBGP peers that lack it, and ensures thatthe added policy is placed at the beginning of the import policy chain.

    /* add-block-privates.slax */version 1.0;

    ns junos = "http://xml.juniper.net/junos/*/junos";ns xnm = "http://xml.juniper.net/xnm/1.1/xnm";ns jcs = "http://xml.juniper.net/junos/commit-scripts/1.0";

    import "../import/junos.xsl";

    match configuration {

    /* Retrieve AS Number */ var $asn = routing-options/autonomous-system/as-number;

    /* Scroll through all EBGP groups */ for-each( protocols/bgp/group[ peer-as != $asn ] ) { if( jcs:empty( import[1][. == "block-private-ranges" ] ) ) { var $content = { /* Add and insert at beginning */ if( count( import ) > 0 ) { var $current-first = import[1]; "block-private-ranges"; } /* Just add */ else {

  • 8/13/2019 Applying Junos Configuration Automation