Mikrotik Scripting: Using the "place-before" parameter to place fw rule "after" other rule
This is a quick trick to programmatically place firewall rules after specific rules, not before.
Normally you already have the place-before parameter when adding firewall rules, but there can be times when you programmatically need to place the rule after another specific rule.
Assumed you want to insert a new rule after the common "established, related" states firewall rule in the input chain, you could do this
This places the rule after it. It makes use of the .nextid property of the entry to get the internal id of the next item in the list. This also works when the rule is the last one in the chain, because the .nextid property will then automatically receive the maximum internal id reference *ffffffff.
The above oneliner assumes that a specific rule already exists, otherwise this command will fail. So to be secure you normally want to do a check if the rule exists:
Regards @colinardo
Normally you already have the place-before parameter when adding firewall rules, but there can be times when you programmatically need to place the rule after another specific rule.
Assumed you want to insert a new rule after the common "established, related" states firewall rule in the input chain, you could do this
/ip firewall filter add chain=input protocol=tcp dst-port=22 action=accept place-before=([get ([find chain=input && connection-state ~ "established"]->0)]->".nextid")
This places the rule after it. It makes use of the .nextid property of the entry to get the internal id of the next item in the list. This also works when the rule is the last one in the chain, because the .nextid property will then automatically receive the maximum internal id reference *ffffffff.
The above oneliner assumes that a specific rule already exists, otherwise this command will fail. So to be secure you normally want to do a check if the rule exists:
{
:local rule ([/ip firewall filter find chain=input && connection-state ~ "established"]->0)
:if ($rule) do={
/ip firewall filter add chain=input protocol=tcp dst-port=22 action=accept place-before=([get $rule]->".nextid")
} else={
:error "Rule not found!"
}
}
Regards @colinardo
Please also mark the comments that contributed to the solution of the article
Content-ID: 671367
Url: https://rootdb.com/tutorial/mikrotik-scripting-using-the-place-before-parameter-to-place-fw-rule-after-other-rule-671367.html
Printed on: February 22, 2025 at 17:02 o'clock