← Blog

Manage DNS records from a script

A short Python script that syncs records from a YAML file using an API token.

[Author name]2 min read

Clicking through a panel is fine for one record. For a zone that changes with every deploy, it is easier to keep the records in a file next to your code and let a script apply them. Here is a minimal version in Python.

What you need

  • A zone in Himk DNS. See Add a zone.
  • An API token, created in the panel at my.himk.am. See API tokens.
  • Python 3 with the requests and PyYAML packages: pip install requests pyyaml.

The records file

Describe the zone and the records you want in records.yaml:

yaml
zone: example.am
records:
  - type: A
    name: www
    content: 203.0.113.10
    ttl: 3600
  - type: A
    name: api
    content: 203.0.113.20
    ttl: 300
  - type: CNAME
    name: blog
    content: www.example.am.
    ttl: 3600

The script

The script reads the file, fetches the records that already exist in the zone and creates the ones that are missing:

python
import os
import sys

import requests
import yaml

API = "https://api.himk.am/v1"
HEADERS = {"Authorization": f"Bearer {os.environ['HIMK_TOKEN']}"}


def key(record):
    return (record["type"], record["name"], str(record["content"]))


def sync(path):
    with open(path) as f:
        config = yaml.safe_load(f)
    url = f"{API}/zones/{config['zone']}/records"

    resp = requests.get(url, headers=HEADERS, timeout=10)
    resp.raise_for_status()
    existing = {key(r) for r in resp.json()}

    for record in config["records"]:
        if key(record) in existing:
            print("exists ", *key(record))
            continue
        resp = requests.post(url, headers=HEADERS, json=record, timeout=10)
        resp.raise_for_status()
        print("created", *key(record))


if __name__ == "__main__":
    sync(sys.argv[1] if len(sys.argv) > 1 else "records.yaml")

It assumes the list endpoint returns an array of records with the same type, name, content and ttl fields. Check the DNS API reference for the exact request and response formats.

Run it

bash
export HIMK_TOKEN="your-token"
python sync_records.py records.yaml

Running it twice is safe: records that already exist are skipped. The script only adds records. Updating or deleting records that are no longer in the file is a small extension once you have this working; the API reference lists the endpoints for both.

Treat the token like a password In CI, store HIMK_TOKEN as a secret variable, not in the repository. Use a separate token for each pipeline so you can revoke one without breaking the others.

Try HimkNew accounts get X XXX ֏ wallet credit.
Sign up

Related posts