Skip to content

Instantly share code, notes, and snippets.

@pietromoro
Created August 5, 2023 10:21
Show Gist options
  • Save pietromoro/bd7fbe8e477248891034b33e355916f9 to your computer and use it in GitHub Desktop.
Save pietromoro/bd7fbe8e477248891034b33e355916f9 to your computer and use it in GitHub Desktop.
Update Porkbun DNS via API (effectiverly creating a DDNS)
#!/bin/bash
# Tempfile that contains the last ip set
tempfile=currentip.tmp
touch $tempfile
last_ip=`cat $tempfile`
echo "Last IP: $last_ip"
curl -X GET "https://v4.ident.me" > $tempfile
current_ip=`cat $tempfile`
echo "Current IP: $current_ip"
# Fill in these with your data!
api_key=pb_key
secret_key=sk_key
record_id=123
domain=example.com
subdomain=test
if [ $last_ip != $current_ip ]; then
echo "Updating DNS record"
# curl -X POST "https://porkbun.com/api/json/v3/ping" -d "{\"secretapikey\": \"$secret_key\", \"apikey\": \"$api_key\"}"
curl -X POST "https://porkbun.com/api/json/v3/dns/edit/$domain/$record_id" -d "{\"secretapikey\": \"$secret_key\", \"apikey\": \"$api_key\", \"content\": \"$current_ip\", \"type\": \"A\", \"name\": \"$subdomain\"}"
fi
@pietromoro
Copy link
Author

Usage

Create an API key from here: https://porkbun.com/account/api
Fill the api_key and secret_key variables in the script with the values you got from the website. Make sure there are no trailing whitespaces.
Make sure you have enabled API Access in your domain.
Create a new DNS record of type A and give it the name you want (ie test). Then you can use the following command to get its id:

curl -X POST https://porkbun.com/api/json/v3/dns/retrieve/example.com -d '{"secretapikey": "YOURSECRETKEY", "apikey": "YOURAPIKEY"}'

Change it to fit your domain (ie: example.com to myowndomain.com) and fill in the secret key and the api key. You'll get a response that looks like this: (this is prettified)

{
	"status": "SUCCESS",
	"records": [
		{
			"id": "123",
			"name": "example.com",
			"type": "A",
			"content": "1.1.1.1",
			"ttl": "600",
			"prio": "0",
			"notes": ""
		},
		{
			"id": "456",
			"name": "www.example.com",
			"type": "A",
			"content": "1.1.1.1",
			"ttl": "600",
			"prio": "0",
			"notes": ""
		}
	]
}

Get the ID of the subdomain you want to setup dynamic DNS and change record_id in the script to that value. Also change subdomain to match your subdomain name.

Supposing you place the script in /usr/bin/dyndns/update_dns.sh run the following:

sudo chmod +x update_dns.sh

This will make the script executable. Next set up the cron to update the DNS every 15 minutes:

$ sudo crontab -e

*/15 * * * * /usr/bin/dyndns/update_dns.sh >/dev/null 2>&1

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment