Skip to content

Instantly share code, notes, and snippets.

@nikhita
Forked from whitlockjc/k8s-namespace-watcher.js
Created September 5, 2017 19:40
Show Gist options
  • Save nikhita/74dc1b2905ac9eba202920976a4ffd84 to your computer and use it in GitHub Desktop.
Save nikhita/74dc1b2905ac9eba202920976a4ffd84 to your computer and use it in GitHub Desktop.
Simple Node.js example of how to use a Kubernetes watcher
'use strict';
const fs = require('fs')
const http = require('http')
const K8S_HOST = process.env['K8S_HOST'] || '10.100.0.1'
const K8S_SECRET = process.env['K8S_SECRET'] ||
fs.readFileSync('/var/run/secrets/kubernetes.io/serviceaccount/token', 'utf-8')
var req = http.request({
protocol: 'http:',
host: K8S_HOST,
port: 8080,
method: 'GET',
path: '/api/v1/namespaces?watch=true',
headers: {
Authorization: 'Bearer ' + K8S_SECRET
}
}, (res) => {
console.log('Watching namespace events...')
res.setEncoding('utf8')
res.on('data', (chunk) => {
const rawEvents = chunk.split('\n')
rawEvents.forEach(function (rawEvent) {
if (rawEvent.length > 0) {
const event = JSON.parse(rawEvent)
console.log(' %s was %s', event.object.metadata.name, event.type.charAt(0) + event.type.substring(1).toLowerCase())
}
})
})
res.on('end', () => {
console.log(' Event stream closed...')
})
})
req.on('error', (err) => {
console.log('Problem with request: %s', err.message)
});
req.end()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment