Forked from davemcdermid/update-route53-on-instance-start.js
Created
June 28, 2017 08:10
-
-
Save Guik/353ea5f096aab86208a69f434a011c49 to your computer and use it in GitHub Desktop.
An AWS lambda function to update a Route53 hosted zone with a CNAME to an EC2s public DNS hostname on instance start. Should be triggered by a CloudWatch event.
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
| var AWS = require('aws-sdk'); | |
| var domain = '.example.com'; | |
| var hostedZone = 'HOSTEDZONEID'; | |
| exports.handler = function(event, context, callback) { | |
| var ec2 = new AWS.EC2(); | |
| var params = { | |
| InstanceIds : [ | |
| event.detail['instance-id'] | |
| ] | |
| }; | |
| ec2.describeInstances(params, function (err, data) { | |
| if (err) console.log(err, err.stack); | |
| else { | |
| var subdomain = data.Reservations[0].Instances[0].Tags.filter(function(p){return p.Key == "SubDomain"})[0]; | |
| var hostname = data.Reservations[0].Instances[0].PublicDnsName; | |
| console.log("subdomain: " + (subdomain ? subdomain.Value : null)); | |
| console.log("new hostname: " + hostname); | |
| if (hostname && subdomain) { | |
| var route53 = new AWS.Route53(); | |
| route53.changeResourceRecordSets({ | |
| HostedZoneId : hostedZone, | |
| ChangeBatch : { | |
| Changes : [{ | |
| Action: 'UPSERT', | |
| ResourceRecordSet: { | |
| Name: subdomain.Value + domain, | |
| Type: 'CNAME', | |
| ResourceRecords: [ | |
| { | |
| Value: hostname | |
| } | |
| ], | |
| TTL: 300 | |
| } | |
| }] | |
| } | |
| }, function (err, data) { | |
| if (err) | |
| console.log(err, err.stack); | |
| else { | |
| console.log('success'); | |
| } | |
| }); | |
| } | |
| } | |
| }); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment