AWS Lambda function that automatically associates a specific Elastic IP address to EC2 instances when they are successfully launched by an Auto Scaling group.
This Lambda function responds to EC2 instance launch events from AWS Auto Scaling groups and associates a pre-configured Elastic IP address to instances that match specific tag filters. This is particularly useful for applications running on EC2 Spot instances where the IP address needs to remain consistent across instance replacements.
Note: This is primarily a learning project. For production environments, consider using AWS Load Balancers for more robust solutions.
When running applications on EC2 Spot instances, AWS may terminate, stop, or hibernate instances when capacity is needed. This function ensures that the Elastic IP address is automatically reassociated to newly launched instances, maintaining a consistent public IP for your application.
- Trigger: EventBridge rule monitoring
EC2 Instance Launch Successfulevents from AWS Auto Scaling - Handler: Lambda function filters instances by tags and associates the configured EIP
- Runtime: Node.js 18.x
- AWS Services: EC2, EventBridge, Lambda
├── src/
│ ├── aws-clients/
│ │ └── ec2client.mjs # EC2 client wrapper functions
│ ├── events/
│ │ └── instancelaunch.json # Sample event for testing
│ ├── handlers/
│ │ ├── app.mjs # Main Lambda handler
│ │ └── config.json # EIP configuration
│ └── schema/
│ └── aws.autoscaling.instance.launch.successful.json
├── template.yaml # AWS SAM template
├── package.json # Node.js dependencies
└── env.json # Environment variables for local testing
The function uses the following environment variables (configured in template.yaml):
- Region: AWS region (default:
eu-central-1) - TagsFilter: Tag value to identify target instances (default:
example-tag)
The Elastic IP allocation ID is configured in src/handlers/config.json.
Deploy using AWS SAM CLI:
sam build
sam deploy --guidedDuring deployment, you'll be prompted to configure:
- Stack name
- AWS region
- CloudFormation capabilities (CAPABILITY_IAM required)
The Lambda function requires the following permissions:
AWSLambdaBasicExecutionRole- CloudWatch Logs accessAmazonEC2ReadOnlyAccess- Read EC2 instance details and tags- Custom policy to associate Elastic IP addresses
Test locally using AWS SAM CLI:
sam local invoke EC2LaunchFunction --event src/events/instancelaunch.json@aws-sdk/client-ec2: ^3.312.0jest: ^29.2.1 (dev dependency)
To delete the deployed application:
aws cloudformation delete-stack --stack-name <your-stack-name>