How to automatically assign/remove Elastic IPs to EC2 Instances upon start/stop

Question:

I am stopping my EC2 instances at night and restart them in the morning using CloudWatch Rules, however the public DNS/IP changes when we restart.

I want to use Elastic IPs and associate the with the instances.

I have read that we need to re-associate the Elastic IPs once the VM is restarted. I want to automate this. I got this lambda python code(Stop and Start EC2 Instances) to start the VM.

What should I do to assign the Elastic IPs also to the VMs while restarting?

Here is my code so far

import boto3
region = 'us-west-1'
instances = ['i-12345cb6de4f78g9h', 'i-08ce9b2d7eccf6d26']
ec2 = boto3.client('ec2', region_name=region)

def lambda_handler(event, context):
    ec2.start_instances(InstanceIds=instances)
    print('started your instances: ' + str(instances))

Please help. And also suggest if any other method is available to achieve this.
Thanks in advance!

Asked By: Harshit Gupta

||

Answers:

If you attach an elastic IP address to your instance, everytime you stop and start the instance the EIP will remain attached.

You do not need to automate adding an EIP on startup.

Take a read of this to familiarize yourself more with elastic IP address functionality.

Answered By: Chris Williams