This seems like an obvious question but I've had no luck finding an answer.
Using Terraform (v1.3.5) and given a private AWS subnet (defined by aws_subnet
), how can I get the next available IP address within the subnet?
I'm sure I'm just looking at the problem wrong. I would expect a resource-type that would take a subnet-id and return an IP address, but can't find one that matches. I've also looked for tutorials on the question. Many tutorials talk about assigning an EIP, but that is for public subnets. I need to allocate several instances within a private subnet and need to allocate addresses for each.
My next question, of course, will be: how to request IPs across a set of subnets with an even allocation across the subnets. But that may need another posting.
Edit #1: In response to the questions from @Marcin and @MattBlaha. I need the IP address to satisfy the requirement for an ENI which is needed to create the instance (see docs here). I've copied the sample code from the docs. Note that a "private_ips" address is required to create the ENI. And the ENI is needed to create the instance:
resource "aws_subnet" "my_subnet" {
vpc_id = aws_vpc.my_vpc.id
cidr_block = "172.16.10.0/24"
availability_zone = "us-west-2a"
tags = {
Name = "tf-example"
}
}
resource "aws_network_interface" "foo" {
subnet_id = aws_subnet.my_subnet.id
private_ips = ["172.16.10.100"]
tags = {
Name = "primary_network_interface"
}
}
resource "aws_instance" "foo" {
ami = "ami-005e54dee72cc1d00" # us-west-2
instance_type = "t2.micro"
network_interface {
network_interface_id = aws_network_interface.foo.id
device_index = 0
}
}
Is there some way to create an ENI with out specifying the IP?
There is no such functionality in TF nor even AWS API. You have to implement your own custom solution to get "next free IP address" from a given subnet. This will be changeling, as you can have a pre-existing resources in the subnet, so you have to get their IP addresses first, before you can find which one is "next" or "free".
The custom solution can be implemented as an external data source in a programing language of your choice, e.g. bash script, python.