That CIDR error is coming from the AWS EC2 API rather than from Terraform, so it suggests that your CIDR block is not within the requirements set by the EC2 API. According to the documentation section VPC and Subnet Sizing for IPv4, the longest prefix length permitted for a subnet is
/28, so your
/30 prefix is too long to fit within that requirement. You’ll need to select a shorter prefix.
Although in principle you can select a specific IP address from the target subnet when declaring an
aws_instance resource, that usage pattern is very uncommon. Instead, we usually leave the specific IP address unspecified and let the VPC system in AWS allocate an unused IP address automatically, which then avoids the need to centrally plan exact IP addresses for all of your instances. If you let the VPC API automatically select an IP address for you, you can then refer to the allocated IP address elsewhere in the configuration with an expression like
aws_instance.example.private_ip, and thus allow other parts of the configuration to automatically use whichever IP address was selected.
If you do have an unusual situation where selecting a specific IP address is required, you can do this by setting the
private_ip argument within the
resource "aws_instance" ... block, like this:
# Use the second IP address available in the containing subnet
private_ip = cidrhost(aws_subnet.example.cidr_block, 2)
cidrhost function calculates an IP address by appending a particular host number to a CIDR prefix.
Your code examples were corrupted a little because you didn’t mark them as being “Preformatted text” (the
<> button in the editor toolbar), so I’ve written the above assuming you declared your subnet as
resource "aws_instance" "example". I expect you’ve used a different name than “example” in practice, so you’ll need to substitute whatever name you selected.