AWS EIP (Elastic IP Assignment Script)
Luke Hebert
- 2 minutes read - 225 wordsIf you need a consistent public IP on an EC2 instance without manually juggling Elastic IPs in the console, this script handles it for you at launch. It runs through the instance User Data, allocates a new Elastic IP, and associates it with the instance in a single pass.
How It Works
When an EC2 instance boots, AWS executes the User Data script once. This script uses the AWS CLI to:
- Allocate a new Elastic IP address.
- Associate that Elastic IP with the instance’s network interface.
Because the script runs at startup, the instance always gets a stable public IP without any manual intervention or external orchestration.
Usage
Paste the script into the User Data field when launching your EC2 instance (or update it via the console for an existing instance and reboot). Make sure the instance’s IAM role has the ec2:AllocateAddress and ec2:AssociateAddress permissions.
Script
Things to Keep in Mind
User Data runs only once per instance launch. If you stop and start the instance, the script will not re-run. If you need the IP to persist across stop/start cycles, the Elastic IP association itself is persistent, so the IP stays attached.
Each Elastic IP you allocate but do not associate with a running instance incurs an hourly charge from AWS. Clean up unused EIPs to avoid unexpected costs.