I use cookies in order to optimize my website and continually improve it. By continuing to use this site, you are agreeing to the use of cookies.
You can find an Opt-Out option and more details on the Privacy Page!

Communicate with an etcd cluster

In the previous post I wrote how to setup an etcd cluster on DigitalOcean. Now I try to communicate to the etcd cluster with NodeJS. There are many libraries on npm that allows communication to an etcd cluster. In this post we use node-etcd, that is easy to use and to setup:

First we need to install it as dependency via npm install node-etcd, after this we can connect to the etcd cluster:

let Etcd = require('node-etcd'),
    fs = require('fs');

var options = {
    ca: fs.readFileSync('../certificate/root/ca.pem'),
    cert: fs.readFileSync('../certificate/client/client.pem'),
    key: fs.readFileSync('../certificate/client/client-key.pem')

let etcd = new Etcd("https://etcd-server-0.koudingspawn.de:2379", options);

We use x509 Certificate authentication to communicate to the etcd cluster. Therefore we specify the location were our certificates and key are placed and load them as. In this example we only specify one member to communicate with, as alternative we can also specify a list of members to failover in case of etcd problems:

var members = ["https://etcd-server-0.koudingspawn.de:2379", "https://etcd-server-0.koudingspawn.de:2379"];
let etcd = new Etcd(members, options);

After this we can set, get and delete key-value pairs or create or delete directories.

This short example writes a key called city with a value Wesel and returns an error object if the write to etcd fails with an exception.

etcd.set('city', 'Wesel', (err) => {});

After this we can read the value of city:

etcd.get('city', (err, data) => {
    // => Wesel

We can also write an object with a time to live (ttl), after this ttl the object will be removed from etcd. In this example the city-key has a time to live of 5 seconds. After this the key-value pair will be removed.

etcd.set('city', 'Wesel', {ttl: 5}, (err) => {});

To delete the created city object we can call the following code:

etcd.del('city', (err) => {});
Björn Wenzel

Björn Wenzel

My name is Björn Wenzel. I’m a Platform Engineer working for Schenker with interests in Kubernetes, CI/CD, Spring and NodeJS.