Monday, June 27, 2016

An alternative to dynamic dns using consul

If you have a remote system, behind a dynamic IP and need to access it, you can use one of the dynamic DNS providers.
What happens if your dynamic DNS suddenly stops working?

There is an alternative, provided you have access to a consul server.

You can set up your system to push its IP to the consul server (either the service backend, or the Key/Value store).

The following example is using the KV store

You can use the following commands in your remote system:

First of all you need to retrieve your external IP:

EXTERNAL_IP=$(curl "")

and then you need to push it to your consul server

curl -X PUT -d "$EXTERNAL_IP" http://consul-server/v1/kv/keyname/externalIP

You can set up this to be executed every now and then in order to update the key every time it changes by your provider.

these data can then be consumed by another script from any other system that need access to your remote system:

curl -s http://consul-server/v1/kv/keyname/externalIP|grep -Po '"Value":.*?[^\\]",'|awk -F: '{print $2}'|tr -d '",'|base64 -d|tr -d '%'

to retrieve the IP of the remote system.
You can then use this either directly, or put it in /etc/hosts or any other system you like.

Just keep in mind that you also need to execute this often since your ISP will change the remote IP relatively often (e.g a couple times per day)