Bulk import DNS data into pfSense

If you are trying to bulk import your current DNS data into pfSense, the built-in pfSense shell comes in handy.

First, get your current data into a file with 2 columns like this:

name.domain.com.  192.168.1.1
name2.domain2.com. 192.168.2.1
name3.domain2.de. 192.168.2.2

Then run the following script – modify it to your needs – which will print out the commands for the pfSense shell:

echo "global \$config;"
echo "parse_config(true);"

index=0
cat alldns.txt | while read name ip
do
  hostname=$(echo $name | cut -d '.' -f 1)
  domain=$(echo $name | cut -d '.' -f 2- | sed -e 's/\.$//')

  echo "\$config['unbound']['hosts']['$index']['host']=\"$hostname\";"
  echo "\$config['unbound']['hosts']['$index']['domain']=\"$domain\";"
  echo "\$config['unbound']['hosts']['$index']['ip']=\"$ip\";"
  echo "\$config['unbound']['hosts']['$index']['descr']=\"Automatically migrated\";"

  let index=$index+1
done
echo "write_config();"
echo "exec"

This will generate the following output, ready to paste into the pfSense shell:

global $config;
parse_config(true);
$config['unbound']['hosts']['0']['host']="name";
$config['unbound']['hosts']['0']['domain']="domain.com";
$config['unbound']['hosts']['0']['ip']="192.168.1.1";
$config['unbound']['hosts']['0']['descr']="Automatically migrated";
$config['unbound']['hosts']['1']['host']="name2";
$config['unbound']['hosts']['1']['domain']="domain2.com";
$config['unbound']['hosts']['1']['ip']="192.168.2.1";
$config['unbound']['hosts']['1']['descr']="Automatically migrated";
$config['unbound']['hosts']['2']['host']="name3";
$config['unbound']['hosts']['2']['domain']="domain2.de";
$config['unbound']['hosts']['2']['ip']="192.168.2.2";
$config['unbound']['hosts']['2']['descr']="Automatically migrated";
write_config();
exec

Please keep in mind the index starts at 0, valid for an empty list of host names in your pfSense Unbound/DNS configuration. For each already existing entry you have to add 1 to the starting index of 0.