Script for adding DNS entries to an address list fails.

Hello. The following script fails when an already existing entry is being added to an address list. I think the conditional :if expression should prevent the error. Failure message: already have such entry
Is something wrong or missing in the script?

Using RouterOS 6.45.8

# Use DNS Entrys and add Address to the Firewall Address-list #
:foreach i in=[/ip dns cache all find where (name~"tiktok") && (static=no)] do={
 :local tmpDomainName [/ip dns cache get $i name];
 delay delay-time=3000ms
 :if ( [/ip firewall address-list find where address=$tmpDomainName] = "") do={ 
 :log info ("added entry: $tmpDomainName");
 /ip firewall address-list add address=$tmpDomainName list=tiktok-hosts; } }

Your script has an error.

:local tmpDomainName [/ip dns cache get $i > name> ];

This “name” will get the name of the host and store it to variable "tmpDomainName "

Then this will fail, since “address” is an IP address

:if ( [/ip firewall address-list find where > address> =$tmpDomainName] = “”) do={

You need to change line to:

:local tmpDomainName [/ip dns cache get $i > address> ]

PS you do not need semicolon at the end of lines. Only needed when separating various commands on one line.


This should do. PS your IP may be in several address list, so better test if its on correct list, and if not add it.

:foreach i in=[/ip dns cache all find where (name~"tiktok") && (static=no)] do={
	:local tmpIP [/ip dns cache get $i address]
	if ([:len [/ip firewall address-list find where address=$tmpIP list=tiktok-hosts]]=0) do {
		/ip firewall address-list add address=$tmpIP list=tiktok-hosts
		:log info ("added entry: $tmpIP")
	}
}

I think it should work with som less parentheses as well:

:foreach i in=[/ip dns cache all find where name~"tiktok" && static=no] do={
	:local tmpIP [/ip dns cache get $i address]
	if ([:len [/ip firewall address-list find where address=$tmpIP list=tiktok-hosts]]=0) do {
		/ip firewall address-list add address=$tmpIP list=tiktok-hosts
		:log info "added entry: $tmpIP"
	}
}

I was able to verify that the original script was running as expected, just, for some reason, ending with a failure message that wasn’t allowing the execution of the next scripts set on a scheduler. I solved the issue wrapping the script:

:do {
	...
} on-error={};

I don’t know if this is the best solution however.

Thank you Jotne for helping me improving the code syntax. I just have some doubts about when use and when don’t use the “:” (as in :foreach and if), and the same for the “=” after “do” (used only on the first case)

Its better to test ting so you do not end up in error situation. And you should test if the IP is used in the actual list and not in any other access list.
So do the testing.

For the semicolon ; I am 100% sure you do not need it at the end of each line, it was change some time back. I have done some scripting (see my signature), never needed it, never failed do to not used it.