Menu

Show posts

This section allows you to view all posts made by this member. Note that you can only see posts made in areas you currently have access to.

Show posts Menu

Messages - ethan240

#1
I got this working on 25.7.

https://docs.opnsense.org/development/api.html#required-parameters-and-expected-responses
https://docs.opnsense.org/development/api/core/unbound.html
https://192.168.1.1/ui/unbound/overrides

Code below will set a new override, save changes then print all the current overrides.

import requests
from tabulate import tabulate

HOST = "192.168.1.1"
API_KEY = "xxx"
API_SECRET = "xxx"

def record_value(record, rr_type):
  if rr_type == "TXT":
    return record.get("txtdata", "")
  if rr_type == "MX":
    mx = record.get("mx", "")
    prio = record.get("mxprio", "")
    return f"{prio} {mx}".strip()
  return record.get("server", "")


def fqdn(record):
  hostname = record.get("hostname", "")
  domain = record.get("domain", "")
  return ".".join(part for part in [hostname, domain] if part)


def dns_rows(data):
  hosts = data.get("rows")

  rows = []
  for record in hosts:
    rows.append({
      "enabled": "yes" if str(record.get("enabled", "0")) == "1" else "no",
      "type": record.get("rr", ""),
      "name": fqdn(record),
      "value": record_value(record, record.get("rr", "")),
      "ttl": record.get("ttl", ""),
      "description": record.get("description", ""),
      "uuid": record.get("uuid", ""),
    })

  return sorted(rows, key=lambda row: (row["name"], row["type"], row["value"]))

# https://docs.opnsense.org/development/api/core/unbound.html

# set a record
resp_set = requests.post(
  url=f"https://{HOST}/api/unbound/settings/add_host_override",
  auth=(API_KEY, API_SECRET),
  data={
    "host": {
      "description": "description_here",
      "domain": "domain.com",
      "enabled": "1",
      "hostname": "test123",
      "mx": "",
      "mxprio": "",
      "rr": "A",
      "server": "127.0.0.69",
      "ttl": "60",
      "txtdata": ""
    }
  }
)
resp_set.raise_for_status()

# apply/save a record
resp_save = requests.post(
  url=f"https://{HOST}/api/unbound/service/reconfigure/",
  auth=(API_KEY, API_SECRET),
  data={}
)
resp_save.raise_for_status()

# get a list of current records
resp_get = requests.post(
  url=f"https://{HOST}/api/unbound/settings/search_host_override/",
  auth=(API_KEY, API_SECRET),
  data={"current":1,"rowCount":-1,"sort":{}}
)
resp_get.raise_for_status()

print(tabulate(dns_rows(resp_get.json()), headers="keys", tablefmt="github"))
#2
Thanks mitchpleune, that worked for me

Attached images of my config (MAKE SURE TO CLICK APPLY)