Terraform – AWS Assign Pre-existing Elastic IP Address to an EC2 Instance

AWS Terraform

Elastic IP Addresses (EIP) are great as they provide you with a static IP address which you can use for an endpoint to your application, but when you are automating things with Terraform, you don’t want it to be continually re-created or that IP address will change, and if you have DNS records pointing at that IP address, you end up having to change them.

Here is the mark-up that allows you to import a pre-existing Elastic IP address, all you need to do is ensure that the EIP you create has specific tag set, which you can then specify in your Terraform.

Create EIP manually, with name: VPC1_EIP1.

Now you can specify it within your Terraform as below, in this example we’re allocating it to an EC2 Instance called: VPC1-Instance-1.

data "aws_eip" "VPC1-EIP1" {
  filter {
    name   = "tag:Name"
    values = ["VPC1-EIP1"]
  }
}

resource "aws_eip_association" "eip_assoc" {
  instance_id   = aws_instance.VPC1-Instance-1.id
  allocation_id = data.aws_eip.VPC1-EIP1.id
}

Leave a Reply

Your email address will not be published. Required fields are marked *