How to Attach Elastic IP to EC2 Instance using Terrafor

Nipulpatel
3 min readSep 21, 2023

--

what is Elastic IP??

if you launch an EC2 instance in your default VPC, a public IP gets automatically assigned to your instance. You use that to connect to(SSH) your EC2 instance remotely or to access an application on your instance online via public IP or public DNS

But the problem which you might already be aware of is public IPs are dynamic in nature. This means when you stop your instance and start it again, your instance’s public IP changes. Needless to say, you no more can access your instance using your previous public IP.

one of the ways in such cases is to assign an elastic IP to your instance which is a static public IP and will not change on the stop and start of your instance.Elastic IPs are public IPs that are static and associated with your AWS account.

Step 1: Initialize the Provider

Create a directory for your terraform files. Once done, create a new .tf file that will contain the required resources.

First of all, we’ll add the provider declaration to let Terraform know that we’ll be working with the AWS provider.

Step 2: Create an EC2 Instance & Attach Elastic IP to EC2 Instance

We have declared the provider in the previous section. Let’s add an EC2 resource and EIP resource to create one.

save the configuration and Initialize Terraform in your project directory by running:

terraform init

Create an execution plan to ensure everything is set up correctly by running

terraform plan

3 Apply the changes to create the EC2 instance and Elastic IP by running

terraform apply

Validate EIP Association

Ec2 instance

EIP

Select your EC2 instance and click on it to go to the instance details screen.

You can see that public IP and elastic IP is shown as same as you would expect.

stop and start your Ec2 instance. This time you will notice that public IP doesn’t change and is always equal to elastic IP.

Run terraform destroy command. And once you say yes to the prompt, all the created resources are deleted .

--

--

Responses (1)