Extracting a Substring Based on Regular Expression Matching
Adding Global Variables for Availability to the onError Macro
Copyright © 2010, Juniper Networks, Inc.
A string can be extracted from a larger string using the following syntax:
env.getRegexpMatch(stringToMatch, someRegularExpression, occurrence)
This example gets the third occurrence of a sequence of numbers followed by a space,
followed by a sequence of letters within string outputLine:
<# value := env.getRegexpMatch(outputLine, "[0-9]+ [a-zA-Z]+", 3) #>
This example gets the interface value from an interface string:
<# interface := env.getRegexpMatch(interface, "[0-9]+/[0-9]+", 1) #>
Global variables can be set in any macro and retrieved without being explicitly passed
in another macro. The global variable is set with the following syntax:
env.setVar(name, value)
The name is a quoted string and the value can be a character string or number.
The global variable is retrieved with the following syntax:
value := env.getVar(name).
The name is a quoted string and the value is the value stored by an earlier env.setVar.
A macro can contain one onError macro. The onError macro is like any other macro file
template. There can only be one macro with the name onError in the macro file.
In this example, the macro sets a global variable before using it in a configuration
command:
<# badInt #>
<# interface := "9/0" #>
<# env.setVar("interface",interface) #>
config t
interface fast <# interface; '\n' #>
ip add 7.6.5.4 255.255.255.0
<#endtmpl#>
<# onError #>
<# c := env.getVar("interface") #>
<# setoutput console #>
<# "begin output\n" #>
<# "The interface value: ";c; "\n" #>
<# endsetoutput #>
end
<#endtmpl#>
When the macro runs, the global variable interface is set and the interface command
contains an invalid interface value. The CLI reports a syntax error and the macro onError
is called. Within the onError macro, the global variable interface is retrieved.
Chapter 8: Writing CLI Macros
463