Created
October 30, 2020 00:47
-
-
Save RoesWibowo/9eef1293522ccd4617f943a466dce76a to your computer and use it in GitHub Desktop.
Lambda function
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 AWS = require('aws-sdk'); | |
const ssm = new AWS.SSM(); | |
const SSM_DOCUMENT_NAME = process.env.SSM_DOCUMENT_NAME; | |
const SNS_TARGET = process.env.SNS_TARGET; | |
function sleep(ms) { | |
return new Promise((resolve) => { | |
setTimeout(resolve, ms); | |
}); | |
} | |
exports.handler = async (event) => { | |
console.log('Received event: ', JSON.stringify(event)); | |
if (event.source !== 'aws.autoscaling') { | |
console.log('Event is not processed because event.source is not aws.autoscaling'); | |
return; | |
} | |
if (event.detail.LifecycleTransition !== 'autoscaling:EC2_INSTANCE_LAUNCHING') { | |
console.log('Event is not processed because event.detail.LifecycleTransition is not autoscaling:EC2_INSTANCE_LAUNCHING'); | |
return; | |
} | |
const params = { | |
DocumentName: SSM_DOCUMENT_NAME, | |
InstanceIds: [ event.detail.EC2InstanceId ], | |
Parameters: { | |
'ASGNAME': [ event.detail.AutoScalingGroupName ], | |
'LIFECYCLEHOOKNAME': [ event.detail.LifecycleHookName ], | |
'SNSTARGET': [ SNS_TARGET ] | |
}, | |
TimeoutSeconds: 300 | |
}; | |
console.log('Waiting send SSM Document!'); | |
await sleep(30000); | |
console.log('Start after wait 30 seconds!'); | |
try { | |
const result = await ssm.sendCommand(params).promise(); | |
console.log("Result: ", result); | |
} catch(error) { | |
console.error("Error:", error); | |
try { | |
await sleep(90000); | |
console.log('Start again after wait 90 seconds!'); | |
const result = await ssm.sendCommand(params).promise(); | |
console.log("Result: ", result); | |
} catch(error2) { | |
console.error("Error:", error2); | |
try { | |
await sleep(90000); | |
console.log('Start again after wait 90 seconds!'); | |
const result = await ssm.sendCommand(params).promise(); | |
console.log("Result: ", result); | |
} catch(error3) { | |
console.error("Error:", error3); | |
} | |
} | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment