0

Using terraform, I need to add 3 elastic IPs to a single new EC2 instance. The terraform yml will be creating the instance as well as the EIPs.

I have tried to do this as follows:

resource "aws_eip" "server_dev1_eip1" {
  count = length(aws_instance.server_dev1)

  instance = aws_instance.server_dev1.*.id[count.index]
  vpc      = true
  lifecycle {
    prevent_destroy = true
  }
}

resource "aws_eip" "server_dev1_eip2" {
  count = length(aws_instance.server_dev1)

  instance = aws_instance.server_dev1.*.id[count.index]
  vpc      = true
  lifecycle {
    prevent_destroy = true
  }
}

resource "aws_eip" "server_dev1_eip3" {
  count = length(aws_instance.server_dev1)

  instance = aws_instance.server_dev1.*.id[count.index]
  vpc      = true
  lifecycle {
    prevent_destroy = true
  }
}

The above is creating the EIPs, but only associating one with the instance.

Please advise

Alex
  • 35
  • 1
  • 5

2 Answers2

1

You can't assign multiple Elastic IPs to a single Elastic Network Interface (ENI). An EC2 instance only has one ENI by default. You will need to attach more ENIs to the EC2 instance and then attach the Elastic IPs to the ENIs.

Mark B
  • 183,023
  • 24
  • 297
  • 295
  • How would I add multiple ENI's to an instance? – Alex Mar 04 '21 at 17:09
  • @Alex check the 2nd example in the official docs: https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/instance#network-interfaces – Mark B Mar 04 '21 at 17:26
0

How to assign multiple AWS Elastic IPs to a newly created multiple EC2 instance via Terraform

data "aws_ami" "amazon" {
  owners      = ["137112412989"]
  most_recent = true
  filter {
    name   = "name"
    values = ["amzn2-ami-kernel-5.10-hvm-2.0*"]
  }
}

main.tf

module "ec2_instance" {
  source = "terraform-aws-modules/ec2-instance/aws"

  version                = "~> 3.0"
  for_each               = toset(var.ec2_name)
  name                   = each.key
  ami                    = data.aws_ami.amazon.id
  instance_type          = var.instance_type
  iam_instance_profile   = module.iam.name
  key_name               = "super-secret-ssh"
  monitoring             = false
  vpc_security_group_ids = [module.sg.id]
  subnet_id              = module.vpc.public_subnets[0]
  ebs_optimized          = true
}

module "aws_eip" {
  source   = "./modules/eip"
  for_each = toset(var.ec2_name)
  instance = module.ec2_instance[each.key].id
}

modules/eip

resource "aws_eip" "eip" {
  instance = var.instance
  vpc      = true
}

variables.tf

variable "ec2_name" {
  type    = list(string)
  default = ["one", "three" , "whatever"]
}

variable "instance_type" {
  type    = string
  default = t2.micro
}

Three EC2 instances will be created and each will have an attached AWS elastic IP.