MikroTik variables and /import

In the past couple of days I have been configuringĀ  bunch of MikroTik routers. The configurations differ, but they all have a few things in common, and I wanted to record those things in a separate file as variables. My idea was that I could then include the separate file in lots of different scripts using /import, so that changes to these common details would only need to be made in one place.

It turned out not to be as simple as I thought!

I tried using /import, I tried /system script run. No matter what I did, the values of the variables stubbornly refused to be available to the enclosing scripts. The symptom was a syntax error on the first character of the variable name whenever it was referenced.

It turns out that using a variable from another “source” requires re-declaring the variable in the script that will be using it.

Here is a script that sets a variable – let’s call it setvar.rsc:

:global VAR "some value" ;

Here is another script, usevar.rsc, that runs setvar.rsc and outputs the value of the variable that setvar.rsc sets:

/import setvar.rsc
:put $VAR ;

When we run uservar.rsc, we’d expect to see it output “some value”. In fact, after loading <code>setvar.rsc</code> successfully, what happens isĀ a syntax error on the V of “$VAR”.

To fix this, all we need to do is redeclare VAR in usevar.rsc, like this:

/import setvar.rsc
:global VAR ;
:put $VAR ;

This has the nice side effect that not ALL variables from <code>setvar.rsc</code> are available to the <code>usevar.rsc</code> by default; only the ones we choose to “import” by redeclaring them.

It’s not so nice that there is no proper language feature allowing the imported file to stipulate what variables are made available, but for a router scripting language it’s not too bad. At least the “programmer” has to consciously decide which variables to use.

 

Leave a Reply

Your email address will not be published.