Search code examples
amazon-web-servicesterraformterraform-provider-aws

Assign pre-existing static (elastic) IP to EC2 instance


Assuming I have an existing Elastic IP on my AWS account.

For reasons beyond the scope of this question, this EIP is not (and cannot) be managed via Terraform.

I know want to assign this EIP (say 11.22.33.44) to an EC2 instance I create via TF

The traditional approach would to of course create both the EIP and the EC2 instance via TF

resource "aws_eip" "my_instance_eip" {
  instance = "my_instance.id"
  vpc      = true
}

resource "aws_eip_association" "my_eip_association" {
  instance_id   = "my_instance.id"
  allocation_id = "aws_eip.my_instance_eip.id"
}

Is there a way however to let EC2 know via TF that it should be assigned as EIP, 11.22.33.44 that is outside of TF lifecycle?


Solution

  • You can use aws_eip data source to get info of your existing EIP and then use that in your aws_eip_association:

    data "aws_eip" "my_instance_eip" {
      public_ip = "11.22.33.44"
    }
    
    resource "aws_eip_association" "my_eip_association" {
      instance_id   = aws_instance.my_instance.id
      allocation_id = data.aws_eip.my_instance_eip.id
    }