dumb_coder
dumb_coder

Reputation: 325

terraform aws ec2 instance ip address assignment

I have a typical problem with terraform and aws. I have to deploy 26 instances via terraform but they all should have ip address in an increment order.

for example

instance 1: 0.0.0.1
instance 2: 0.0.0.2
instance 3: 0.0.0.3

Is it possible somehow to achieve in terraform?

Upvotes: 0

Views: 2119

Answers (1)

Marcin
Marcin

Reputation: 238081

Below, you can find an example of how to do it. It just creates for instances with ip range from 172.31.64.100 to 172.31.64.104 (you can't use first few numbers as they are reserved by AWS).

You will have to adjust subnet id and initial IP range which I used in my example to your subnets. You also must ensure that these IP addresses are not used. AWS could already use them for its load balances in your VPC, existing instances or other services. If any IP address in this range is already taken, it will fail.

locals {
  ip_range = [for val in range(100, 104): "172.31.64.${val}"]
}

resource "aws_network_interface" "foo" {

  for_each    = toset(local.ip_range)

  subnet_id   = "subnet-b64b8988"
  
  private_ips = [each.key]

  tags = {
    Name = "primary_network_interface"
  }
}

resource "aws_instance" "web" {

  for_each      = toset(local.ip_range)

  ami           = data.aws_ami.ubuntu.id
  instance_type = "t2.micro"
  
  network_interface {
    network_interface_id = aws_network_interface.foo[each.key].id
    device_index         = 0
  }  

  tags = {
    Name = "HelloWorld"
  }
}

Upvotes: 1

Related Questions