Skip to content

Instantly share code, notes, and snippets.

@branneman branneman/index.js
Last active Sep 5, 2018

Embed
What would you like to do?
Updates a DNS record via Gandi's API
#!/usr/bin/env node
const fetch = require('node-fetch')
const ip = require('ip')
const os = require('os')
const env = require('./.env.json')
const endpoint = 'https://dns.api.gandi.net/api/v5/'
const newip = `${ip.address()}`
const domain = env.domain
.split('.')
.slice(0, -2)
.join('.')
const hostname = `${os.hostname()}.${domain}`
const ttl = 300
/**
* App
*/
doesRecordExist()
.then(e => (e ? updateRecord() : createRecord()))
.catch(err => {
process.stderr.write(err + '\n')
process.exit(1)
})
/**
* Does a specific record exist?
*/
function doesRecordExist() {
return apiGetZoneRecords().then(res => {
return !!res.find(
record => record.rrset_name === hostname && record.rrset_type === 'A'
)
})
}
/**
* Create new record for hostname
*/
function createRecord() {
const data = {
rrset_ttl: ttl,
rrset_values: [newip]
}
return apiAddZoneRecord(hostname, 'A', data)
}
/**
* Update existing record with new IP
*/
function updateRecord(domain) {
const data = {
rrset_ttl: ttl,
rrset_values: [newip]
}
return apiUpdateZoneRecord(hostname, 'A', data)
}
/**
* API: list all records for a zone
*/
function apiGetZoneRecords() {
const url = `${endpoint}zones/${env.zoneid}/records`
return fetch(url, {
method: 'GET',
headers: {
'X-Api-Key': env.apikey
}
}).then(res => res.json())
}
/**
* API: add a new zone record
*/
function apiAddZoneRecord(name, t, data) {
const url = `${endpoint}zones/${env.zoneid}/records/${name}/${t}`
return fetch(url, {
method: 'POST',
headers: {
'X-Api-Key': env.apikey,
'Content-Type': 'application/json; charset=utf-8'
},
body: JSON.stringify(data)
}).then(res => res.json())
}
/**
* API: update a single zone record
*/
function apiUpdateZoneRecord(name, t, data) {
const url = `${endpoint}zones/${env.zoneid}/records/${name}/${t}`
return fetch(url, {
method: 'PUT',
headers: {
'X-Api-Key': env.apikey,
'Content-Type': 'application/json; charset=utf-8'
},
body: JSON.stringify(data)
}).then(res => res.json())
}
{
"name": "gandi-update-dns-record",
"version": "1.0.0",
"description": "",
"main": "gandi-update-dns-record.js",
"repository": {
"type": "git",
"url": "git+https://gist.github.com/842ce03721d474a61d3f68036486d568.git"
},
"author": "Bran van der Meer <bran.van.der.meer@protonmail.com>",
"license": "MIT",
"homepage": "https://gist.github.com/842ce03721d474a61d3f68036486d568",
"dependencies": {
"ip": "^1.1.5",
"node-fetch": "^2.2.0"
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.