Persist Private IP in AWS Auto Scaling Group
Recently, we were moving our web application, which was on a single EC2 instance, to a highly available and fault-tolerant architecture. For that, we decided to pre-bake an AMI and launch it within an Auto Scaling group, attached to a target group behind an Elastic Load Balancer. We had another server in the same VPC but not in the target group behind the ELB. The requirement was to access our web application privately within the VPC, due to HIPAA regulatory compliance.
In other words, we needed a way to persist a private IP to the EC2 instance in case of a scale-in or scale-out event. We did some research and came up with a solution: create an instance launch lifecycle event, capture the event using AWS CloudWatch Rules, and use AWS Lambda as a target to attach a secondary ENI to the newly launched EC2 instance in the Auto Scaling group.
Thanks to the AWS Knowledge Center, we were able to modify their solution to fit our needs.
But how does it work?
We needed a way to give the secondary ENI’s description to Lambda so it could attach the specific ENI to the newly launched instance. We decided to get the description of the ENI from an EC2 instance tag. For that, we created a launch configuration for the Auto Scaling group with a tag named Eth1, with a value that is, in fact, the description of the secondary ENI.
-
Create a lifecycle hook on the EC2 instance launch event.

-
Create an AWS CloudWatch Rule with a Lambda function as the target.

The Lambda code
Code: github.com/MrHassanMurtaza/aws-attach-secondary-eni-lambda
Feel free to contribute and change it as per your needs.