Script placement of firewall rules to the first position.

I’m writing a set of scripts that I can use as configuration modules to build other scripts.

In some of the cases, I want to be certain the rule added is first.

If I have this rule:
/ip firewall mangle add chain=prerouting action=add-dst-to-address-list
address-list=“Netflix” address-list-timeout=30m content=nflxvideo.net
place-before=0
comment=“Limit Netflix (Address List)”

it will place the mangle rule first, IF there’s already a filter. If there are no mangle rules, it will error out on the place-before command (because there is no 0-value place-before).

Now I can work around that a few ways. Always creating a placeholder dummy mangle, then adding the mangle I want, then removing the placeholder.

Or running:
:global AllRules [/ip firewall mangle find]
to determine if there are any rules, and then using if statements to run the command with place-before if there are mangle rules, and without place-before if there aren’t mangle rules.

Both of which seem like there should be a better way?

http://forum.mikrotik.com/t/enable-disable-a-firewall-rule-in-terminal-or-script/144097/6

I found also the support request to Mikrotik on this:

Thank you for contacting MikroTik Support.

Adding print to the script is the correct way of letting the script know which line is currently used and based on that it will recognize and use it for inserting the next item.

Simply use place-before=*****0 with or without already defined rules.

Example:

/ip firewall mangle
add action=add-dst-to-address-list address-list=Netflix address-list-timeout=30m chain=prerouting comment="Limit Netflix (Address List)" \
    content=nflxvideo.net place-before=*0

2025 addendum:
https://forum.mikrotik.com/viewtopic.php?p=1132720#p1132671