Skip to content

Instantly share code, notes, and snippets.

@Relecto
Last active February 4, 2019 17:33
Show Gist options
  • Select an option

  • Save Relecto/2c55ec8abb0a9b4141708efe3f8d2ca0 to your computer and use it in GitHub Desktop.

Select an option

Save Relecto/2c55ec8abb0a9b4141708efe3f8d2ca0 to your computer and use it in GitHub Desktop.
Automate deployment with this Node.js script and GitHub webhooks
const http = require('http')
const crypto = require('crypto')
const cp = require('child_process')
// Configuration variables
// secret you set in github settings
const secret = process.env.SECRET
// port to listen for requests
const port = process.env.PORT || 4000
// directory of your project
const dir = process.env.DIR
// branch to pull (optional)
const branch = process.env.BRANCH
// command executed before pull
const postPull = process.env.POST_PULL_CMD
http.createServer((req, res) => {
// Read request body
let body = ''
req.on('data', chunk => {
body += chunk.toString()
})
req.on('end', () => {
// Verify signature of request
let signature = 'sha1=' + crypto.createHmac('sha1', secret).update(body).digest('hex')
if (req.headers['x-hub-signature'] !== signature) {
res.statusCode = 500
res.end('Signature verification failed')
return
}
// Parse body
let payload = JSON.parse(body)
// Check branch
if (branch) {
if (!payload.ref.endsWith(branch)) {
console.log(`${payload.ref} of ${payload.repository.name} will not be deployed`)
res.statusCode = 202
res.end(`${payload.ref} will not be deployed`)
return
}
}
console.log(`Deploying ${payload.ref} of ${payload.repository.name}`)
deploy()
res.end(`${payload.ref} will be deployed`)
})
}).listen(port)
function deploy() {
// Pull
cp.exec(`cd ${dir} && git pull`, (err, stdout, stderr) => {
logExec(err, stdout, stderr)
// Execute post pull command
if (postPull) {
cp.exec(`cd ${dir} && ${postPull}`, logExec)
}
})
}
// Function for logging child_process.exec() callback
function logExec(err, stdout, stderr) {
if (err) {
return console.error(err)
}
if (stdout) {
return console.log(stdout)
}
if (stderr) {
return console.error(stderr)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment