Skip to content

Instantly share code, notes, and snippets.

@whitlockjc
Created May 22, 2017 18:16
Show Gist options
  • Save whitlockjc/0373e7bc9f0e883fab7281d9e1f4f684 to your computer and use it in GitHub Desktop.
Save whitlockjc/0373e7bc9f0e883fab7281d9e1f4f684 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