Last active
July 20, 2016 17:53
-
-
Save mwunsch/c4e18040cbca7ef493e3290f69886dfd to your computer and use it in GitHub Desktop.
CFN Custom Resource - GitHub CodeDeploy webhook
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const response = require('cfn-response'); | |
const http = require('https'); | |
const url = require('url'); | |
exports.handler = function(event, context) { | |
var props = event.ResourceProperties; | |
var options = { | |
hostname: 'api.github.com', | |
headers: { | |
'Accept': 'application/vnd.github.v3+json', | |
'Authorization': `token ${props.GitHubToken}`, | |
'User-Agent': `AWS Lambda - ${event.LogicalResourceId}` | |
} | |
}; | |
if (event.RequestType === 'Create') { | |
var opt = Object.assign({ | |
path: `/repos/${props.GitHubRepo}/hooks`, | |
method: 'POST' | |
}, options); | |
var hook = { | |
name: 'awscodedeploy', | |
events: ['deployment'], | |
config: { | |
application_name: props.ApplicationName, | |
deployment_group: props.DeploymentGroup, | |
aws_access_key_id: props.DeployerAccessKeyId, | |
aws_secret_access_key: props.DeployerSecretAccessKey, | |
aws_region: 'us-east-1' | |
} | |
}; | |
var req = http.request(opt, (res) => { | |
var body = ''; | |
res.on('data', (chunk) => body += chunk.toString()); | |
res.on('end', () => { | |
console.log(`GitHub Status: ${res.statusCode} ${res.statusMessage} ; Body:\n ${body}`); | |
if (res.statusCode === 201) { | |
response.send(event, context, response.SUCCESS, { Value: body }, JSON.parse(body).url); | |
} else { | |
response.send(event, context, response.FAILED); | |
}; | |
}); | |
}); | |
req.setTimeout(500); | |
req.write(JSON.stringify(hook)); | |
req.end(); | |
} else if (event.RequestType === 'Delete') { | |
console.log(`CFN Delete:\n ${JSON.stringify(event)}`); | |
var opt = Object.assign({ | |
path: url.parse(event.PhysicalResourceId).pathname, | |
method: 'DELETE' | |
}, options); | |
var req = http.request(opt, (res) => { | |
var body = ''; | |
res.on('data', (chunk) => body += chunk.toString()); | |
res.on('end', () => { | |
console.log(`GitHub Status: ${res.statusCode} ${res.statusMessage} ; Body:\n ${body}`); | |
if (res.statusCode === 204) { | |
response.send(event, context, response.SUCCESS); | |
} else { | |
response.send(event, context, response.FAILED); | |
}; | |
}); | |
}); | |
req.setTimeout(500); | |
req.end(); | |
} else { | |
/* ¯\_(ツ)_/¯ */ | |
console.log(`CFN Request:\n ${JSON.stringify(event)}`); | |
response.send(event, context, response.SUCCESS); | |
}; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment