Created
October 15, 2022 03:01
-
-
Save diegofcornejo/50b4fddc0164fa9b42149d1f9c468459 to your computer and use it in GitHub Desktop.
AWS Lambda - Automate Elastic IP assignation to new created EC2 instance
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 EC2 = new AWS.EC2(); | |
exports.handler = (event, context, callback) => { | |
const done = function(response) { | |
callback(null, response); | |
}; | |
const message = JSON.parse(event.Records[0].Sns.Message); | |
console.log(message); | |
const describeAddressesParams = { | |
PublicIps: [ | |
'XX.XX.XX.XX', | |
'XX.XX.XX.XX' | |
] | |
}; | |
EC2.describeAddresses(describeAddressesParams, function(err, data) { | |
if (err) { | |
done({ message: 'Error ', error: err }); | |
} | |
else { | |
console.log(data.Addresses); | |
// let i; | |
// for (const i = 0; i < data.Addresses.length; i++) { | |
for (const address of data.Addresses) { | |
if (!address.InstanceId) { | |
const associateAddressParams = { | |
AllocationId: address.AllocationId, | |
InstanceId: message.EC2InstanceId | |
}; | |
EC2.associateAddress(associateAddressParams, function(err, data) { | |
if (err) { | |
done({ message: 'Error ', error: err }); | |
} | |
else { | |
done(data); | |
} | |
}); | |
} | |
} | |
} | |
}); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment