简体   繁体   中英

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

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

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM