'How to assign an AWS Elastic IP to a newly created EC2 instance with Terraform without it getting reassigned when another instance is created?

I currently have the following Terraform plan:

provider "aws" {
  region = var.region
}

resource "aws_instance" "ec2" {
  ami             = var.ami
  instance_type   = var.instanceType
  subnet_id       = var.subnet 
  security_groups = var.securityGroups 

  timeouts {
    create = "2h"
    delete = "2h"
  }

  tags = {
    Name = "${var.ec2ResourceName}"
    CoreInfra = "false"
  }

  lifecycle {
    prevent_destroy = true
  }

  key_name = "My_Key_Name"

  connection {
    type        = "ssh"
    user        = "ec2-user"
    password    = ""
    private_key = file(var.keyPath)
    host        = self.public_ip
  }

  provisioner "file" {
    source      = "/home/ec2-user/code/backend/ec2/setup_script.sh"
    destination = "/tmp/setup_script.sh"
  }

  provisioner "remote-exec" {
    inline = [
      "chmod +x /tmp/setup_script.sh",
      "bash /tmp/setup_script.sh ${var.ec2ResourceName}"
    ]
  }
}

resource "aws_eip" "eip_manager" {
  name = "eip-${var.ec2ResourceName}"
  instance = aws_instance.ec2.id
  vpc = true
  
  tags = {
    Name = "eip-${var.ec2ResourceName}"
  }

  lifecycle {
    prevent_destroy = true
  }
}

This plan can be run multiple times, creating a single EC2 instance each time without removing the previous one. However, there is a single Elastic IP that ends up being reassigned to the most recently-created EC2 instance. How can I add an Elastic IP to each new instance that does not get reassigned?



Solution 1:[1]

maybe with aws_eip_association, here is the snippet:

resource "aws_eip_association" "eip_assoc" {
  instance_id   = aws_instance.ec2.id
  allocation_id = aws_eip.eip_manager.id
}

More info here: https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/eip_association

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 PierrickM