Skip to content

Instantly share code, notes, and snippets.

@diegofcornejo
Created October 15, 2022 03:01
Show Gist options
  • Save diegofcornejo/50b4fddc0164fa9b42149d1f9c468459 to your computer and use it in GitHub Desktop.
Save diegofcornejo/50b4fddc0164fa9b42149d1f9c468459 to your computer and use it in GitHub Desktop.
AWS Lambda - Automate Elastic IP assignation to new created EC2 instance
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