Home > Software engineering >  Assign fixed private IP for ec2 instance in terraform
Assign fixed private IP for ec2 instance in terraform

Time:11-15

I have came up with below:

resource "aws_network_interface" "eni_carl" {
  subnet_id = module.vpc.public_subnets[3]
  private_ip = "10.0.4.1/32"
  security_groups = [module.vpc.ssh_sg]
}

resource "aws_instance" "carl" {
  ami = var.ami
  instance_type = "t2.micro"
  key_name = var.key_name

  network_interface {
    network_interface_id = aws_network_interface.eni_carl.id
    device_index = 0
  }
}

But aws will randomly assign private ip for my instance. How can I achieve generating the same and fixed private ip address for my instance?

Terraform v1.3.4 on linux_amd64

  • provider registry.terraform.io/hashicorp/aws v4.39.0

CodePudding user response:

From aws_instance | Resources | hashicorp/aws | Terraform Registry:

resource "aws_network_interface" "foo" {
  subnet_id   = aws_subnet.my_subnet.id
  private_ips = ["172.16.10.100"]

  tags = {
    Name = "primary_network_interface"
  }
}

Therefore, the parameter appears to be: private_ips = ["172.16.10.100"]

It takes an IP address instead of a CIDR block.

  • Related