
Mastering AWS VPC IPAM in Production: A Complete Guide with IaC, CLI, and Python Automation
AWS VPC IPAM centralizes IP planning and automated allocation across multi-account AWS environments, eliminating CIDR overlaps and enforcing governance. This guide covers production best practices, hierarchical pools, Terraform/CloudFormation IaC, CLI commands, and Python boto3 automation. Includes RAM sharing, compliance monitoring, BYOIP integration, cost tagging, and migration strategies from manual to IPAM-governed infrastructure.
Amazon VPC IP Address Manager (IPAM) is a cornerstone service for enterprises managing IP address space at scale across multi-account, multi-region AWS environments. It eliminates manual CIDR tracking, prevents overlaps, automates allocations, and enforces IP governance—critical for production workloads.
What is AWS VPC IPAM?
AWS VPC IPAM is a centralized IP address management service that helps you plan, track, and allocate IP addresses across your AWS organization. It provides a hierarchical pool structure, automated CIDR allocation, compliance monitoring, and integration with AWS Organizations and Resource Access Manager (RAM).
Key Capabilities
- Centralized IP Inventory: Track all public and private IP addresses across accounts and regions
- Hierarchical Pool Management: Organize IP space by business unit, environment (dev/prod), and region
- Automated CIDR Allocation: Prevent overlaps and enforce netmask constraints
- Compliance Monitoring: Detect non-compliant VPCs, subnets, and IP allocations
- BYOIP Integration: Bring your own public IP space and distribute it across accounts
- Multi-Account Support: Share IPAM pools via AWS RAM across organizational units
Why IPAM Matters in Production
In production environments, IP address mismanagement leads to:
- CIDR Overlaps: Blocked VPC peering, Transit Gateway attachments, and migrations
- IP Exhaustion: Unplanned subnet growth causing deployment failures
- Manual Errors: Spreadsheet-based tracking fails at scale
- Compliance Gaps: Inability to audit IP allocations across accounts
IPAM solves these by providing a single source of truth with automated enforcement.
IPAM Architecture and Hierarchy
IPAM uses a hierarchical pool model with scopes (Public/Private) and nested pools.
Recommended Pool Hierarchy for Production

This structure enables:
- Regional isolation: Separate pools per AWS region
- Environment segmentation: Production vs. non-production CIDRs
- Automatic netmask enforcement: Ensure /18 for prod, /20 for dev, etc.
Production Best Practices
Based on AWS guidance and community best practices:
1. Centralize IPAM in a Network Account
- Deploy IPAM in a dedicated Network Account (not the Management account)
- Use AWS Control Tower to delegate IPAM administration from Management → Network account
- Enable IPAM in all operational regions where you run workloads
2. Enforce IPAM-Based VPC Creation
- Mandatory: All new VPCs must be created from IPAM pools
- Prevent manual VPC creation via Service Control Policies (SCPs)
- Use IPAM's "VPC creation from pool" feature to auto-allocate CIDRs
3. Define Strict Netmask Rules
- Production VPCs: /18 (16,382 IPs) to allow growth
- Non-Prod VPCs: /20 (4,094 IPs) to conserve space
- Subnets: /24 (251 IPs) minimum for production workloads
- Configure these in IPAM pool rules to auto-reject non-compliant allocations
4. Leverage AWS RAM for Multi-Account Access
- Share IPAM pools with OU accounts via AWS RAM
- Accounts must be in the same AWS Organization
- Use resource shares to grant
ec2:CreateVpcpermissions scoped to IPAM pools
5. Monitor Compliance Continuously
- Enable IPAM's compliance checks for VPCs, subnets, and IP allocations
- Set up CloudWatch alarms for non-compliant resources
- Use AWS Config rules to enforce IPAM-based VPC creation
6. Tag Everything
- Apply tags to IPAM pools (e.g.,
Environment=Production,CostCenter=12345)
- Tags propagate to VPC allocations for cost allocation and governance
- Use tags for automation (e.g., "delete all dev pools on Friday")
7. Plan for BYOIP (If Using Public IPs)
- Onboard public CIDRs once via IPAM, then distribute across regions/accounts
- Simplifies CloudFront, ALB, and EC2 public IP management
- Use CLI or Terraform for repeatable BYOIP onboarding
Implementing IPAM with Infrastructure as Code (IaC)
Terraform Configuration
Below is a production-ready Terraform setup for IPAM with hierarchical pools, RAM sharing, and VPC allocation.
# providers.tf
terraform {
required_version = ">= 1.5.0"
required_providers {
aws = {
source = "hashicorp/aws"
version = "~> 5.0"
}
}
}
provider "aws" {
region = "ap-south-1"
# Assume role in Network Account
}
# 1. Create IPAM
resource "aws_vpc_ipam" "production_ipam" {
operating_regions {
region_name = "ap-south-1"
}
operating_regions {
region_name = "us-east-1"
}
tags = {
Name = "Production-IPAM"
Environment = "Production"
ManagedBy = "Terraform"
}
}
# 2. Create Top-Level Private Pool
resource "aws_vpc_ipam_pool" "global_private_pool" {
ipam_scope_id = aws_vpc_ipam.production_ipam.private_default_scope_id
address_family = "ipv4"
description = "Top-level private IP pool for all regions"
auto_import = false
locale = "ap-south-1"
tags = {
Name = "Global-Private-Pool"
Environment = "Production"
}
}
# 3. Create Regional Pool (ap-south-1)
resource "aws_vpc_ipam_pool" "ap_south_1_pool" {
ipam_scope_id = aws_vpc_ipam.production_ipam.private_default_scope_id
address_family = "ipv4"
description = "Private IP pool for ap-south-1 region"
auto_import = false
locale = "ap-south-1"
source_ipam_pool_id = aws_vpc_ipam_pool.global_private_pool.id
# Enforce netmask rules
allocation_default_netmask_length = 18 # Default VPC size
allocation_min_netmask_length = 18
allocation_max_netmask_length = 24
tags = {
Name = "AP-South-1-Private-Pool"
Region = "ap-south-1"
Environment = "Production"
}
}
# 4. Create Production Environment Pool
resource "aws_vpc_ipam_pool" "production_env_pool" {
ipam_scope_id = aws_vpc_ipam.production_ipam.private_default_scope_id
address_family = "ipv4"
description = "Production VPC pool in ap-south-1"
auto_import = false
locale = "ap-south-1"
source_ipam_pool_id = aws_vpc_ipam_pool.ap_south_1_pool.id
allocation_default_netmask_length = 18
allocation_min_netmask_length = 18
allocation_max_netmask_length = 18
tags = {
Name = "Production-Environment-Pool"
Environment = "Production"
CostCenter = "12345"
}
}
# 5. Share IPAM Pool with OU Accounts via RAM
resource "aws_ram_resource_share" "ipam_pool_share" {
name = "IPAM-Pool-Share-Production"
allow_external_principals = false
tags = {
Name = "IPAM-Pool-Share-Production"
}
}
resource "aws_ram_resource_association" "pool_association" {
resource_arn = aws_vpc_ipam_pool.production_env_pool.arn
resource_share_arn = aws_ram_resource_share.ipam_pool_share.arn
}
# Share with specific OU (replace with your OU ARN)
resource "aws_ram_principal_association" "ou_association" {
principal = "arn:aws:organizations::123456789012:ou/o-abc123def4/ou-1234567890abcdef"
resource_share_arn = aws_ram_resource_share.ipam_pool_share.arn
}
# 6. Allocate CIDR from Pool for VPC
resource "aws_vpc_ipam_pool_cidr" "prod_vpc_cidr" {
ipam_pool_id = aws_vpc_ipam_pool.production_env_pool.id
cidr = "10.100.0.0/18" # Or let IPAM auto-allocate by omitting this
}
# 7. Create VPC from IPAM Pool CIDR
resource "aws_vpc" "production_vpc" {
cidr_block = aws_vpc_ipam_pool_cidr.prod_vpc_cidr.cidr
tags = {
Name = "Production-VPC-1"
Environment = "Production"
IpamPoolId = aws_vpc_ipam_pool.production_env_pool.id
}
}
# 8. Create Subnets with IPAM-managed CIDRs
resource "aws_subnet" "prod_subnet_1" {
vpc_id = aws_vpc.production_vpc.id
cidr_block = "10.100.0.0/24"
availability_zone = "ap-south-1a"
tags = {
Name = "Production-Subnet-1"
Environment = "Production"
}
}
resource "aws_subnet" "prod_subnet_2" {
vpc_id = aws_vpc.production_vpc.id
cidr_block = "10.100.1.0/24"
availability_zone = "ap-south-1b"
tags = {
Name = "Production-Subnet-2"
Environment = "Production"
}
}
# 9. Enable IPAM Compliance Monitoring
resource "aws_vpc_ipam_resource_discovery" "ipam_discovery" {
ipam_arn = aws_vpc_ipam.production_ipam.arn
operating_regions {
region_name = "ap-south-1"
}
operating_regions {
region_name = "us-east-1"
}
}
# 10. AWS Config Rule for Non-Compliant IPAM Resources
# IPAM does not publish metrics to CloudWatch; use AWS Config for compliance monitoring
resource "aws_config_config_rule" "vpc_ipam_compliance" {
name = "vpc-ipam-pool-compliance"
source {
owner = "AWS"
source_identifier = "VPC_RESOURCES_MANAGED_BY_IPAM"
}
depends_on = [aws_config_configuration_recorder.main]
}Apply this Terraform:
terraform init
terraform plan -out=ipam.tfplan
terraform apply ipam.tfplanCloudFormation Template (Alternative)
For teams using CloudFormation or AWS Service Catalog:
AWSTemplateFormatVersion: '2010-09-09'
Description: 'Production IPAM Setup with Hierarchical Pools'
Resources:
ProductionIPAM:
Type: AWS::EC2::IPAM
Properties:
OperatingRegions:
- RegionName: ap-south-1
- RegionName: us-east-1
Tags:
- Key: Name
Value: Production-IPAM
- Key: Environment
Value: Production
GlobalPrivatePool:
Type: AWS::EC2::IPAMPool
Properties:
IpamScopeId: !GetAtt ProductionIPAM.PrivateDefaultScopeId
AddressFamily: ipv4
Description: 'Top-level private IP pool'
AutoImport: false
Locale: ap-south-1
Tags:
- Key: Name
Value: Global-Private-Pool
APSouth1RegionalPool:
Type: AWS::EC2::IPAMPool
Properties:
IpamScopeId: !GetAtt ProductionIPAM.PrivateDefaultScopeId
AddressFamily: ipv4
Description: 'Private pool for ap-south-1'
AutoImport: false
Locale: ap-south-1
SourceIpamPoolId: !GetAtt GlobalPrivatePool.IpamPoolId
AllocationDefaultNetmaskLength: 18
AllocationMinNetmaskLength: 18
AllocationMaxNetmaskLength: 24
Tags:
- Key: Name
Value: AP-South-1-Private-Pool
ProductionEnvPool:
Type: AWS::EC2::IPAMPool
Properties:
IpamScopeId: !GetAtt ProductionIPAM.PrivateDefaultScopeId
AddressFamily: ipv4
Description: 'Production VPC pool'
AutoImport: false
Locale: ap-south-1
SourceIpamPoolId: !GetAtt APSouth1RegionalPool.IpamPoolId
AllocationDefaultNetmaskLength: 18
AllocationMinNetmaskLength: 18
AllocationMaxNetmaskLength: 18
Tags:
- Key: Name
Value: Production-Environment-Pool
- Key: CostCenter
Value: '12345'
Outputs:
IpamArn:
Description: 'IPAM ARN'
Value: !Ref ProductionIPAM
ProductionPoolId:
Description: 'Production Environment Pool ID'
Value: !Ref ProductionEnvPoolAWS CLI Commands for IPAM Operations
1. Create IPAM
aws ec2 create-ipam \
--operating-regions RegionName=ap-south-1 RegionName=us-east-1 \
--tag-specifications 'ResourceType=ipam,Tags=[{Key=Name,Value=Production-IPAM},{Key=Environment,Value=Production}]' \
--region ap-south-1Output: Save the
IpamArn for subsequent commands.2. Create Top-Level Private Pool
# First, get the private scope ID from your IPAM
PRIVATE_SCOPE_ID=$(aws ec2 describe-ipam-scopes \
--filters Name=ipam-arn,Values=arn:aws:ec2::123456789012:ipam/ipam-abc123def456 \
Name=ipam-scope-type,Values=private \
--query 'IpamScopes[0].IpamScopeId' --output text --region ap-south-1)
aws ec2 create-ipam-pool \
--ipam-scope-id $PRIVATE_SCOPE_ID \
--address-family ipv4 \
--description "Top-level private IP pool" \
--locale ap-south-1 \
--tag-specifications 'ResourceType=ipam-pool,Tags=[{Key=Name,Value=Global-Private-Pool}]' \
--region ap-south-13. Create Regional Pool with Netmask Rules
aws ec2 create-ipam-pool \
--ipam-scope-id $PRIVATE_SCOPE_ID \
--address-family ipv4 \
--description "Private pool for ap-south-1" \
--locale ap-south-1 \
--source-ipam-pool-id ipam-pool-xyz789 \
--allocation-default-netmask-length 18 \
--allocation-min-netmask-length 18 \
--allocation-max-netmask-length 24 \
--tag-specifications 'ResourceType=ipam-pool,Tags=[{Key=Name,Value=AP-South-1-Pool},{Key=Region,Value=ap-south-1}]' \
--region ap-south-14. Allocate CIDR from Pool
Manual CIDR:
aws ec2 provision-ipam-pool-cidr \
--ipam-pool-id ipam-pool-prod123 \
--cidr 10.100.0.0/18 \
--region ap-south-1Auto-allocate (let IPAM pick):
aws ec2 provision-ipam-pool-cidr \
--ipam-pool-id ipam-pool-prod123 \
--netmask-length 18 \
--region ap-south-15. Create VPC from IPAM Pool
aws ec2 create-vpc \
--ipv4-ipam-pool-id ipam-pool-prod123 \
--ipv4-netmask-length 18 \
--tag-specifications 'ResourceType=vpc,Tags=[{Key=Name,Value=Production-VPC-1},{Key=IpamPoolId,Value=ipam-pool-prod123}]' \
--region ap-south-16. Share Pool via RAM
# Create resource share
aws ram create-resource-share \
--name IPAM-Pool-Share-Production \
--resource-arns arn:aws:ec2::123456789012:ipam-pool/ipam-pool-prod123 \
--principals arn:aws:organizations::123456789012:ou/o-abc123/ou-xyz789 \
--region ap-south-17. Check IPAM Compliance
# Get the private scope ID first
PRIVATE_SCOPE_ID=$(aws ec2 describe-ipam-scopes \
--filters Name=ipam-arn,Values=arn:aws:ec2::123456789012:ipam/ipam-abc123 \
Name=ipam-scope-type,Values=private \
--query 'IpamScopes[0].IpamScopeId' --output text --region ap-south-1)
aws ec2 get-ipam-resource-cidrs \
--ipam-scope-id $PRIVATE_SCOPE_ID \
--filters Name=compliance-status,Values=noncompliant \
--region ap-south-18. List IPAM Pools and Usage
# List all pools
aws ec2 describe-ipam-pools \
--filters Name=scope,Values=private \
--region ap-south-1
# Check pool utilization
aws ec2 describe-ipam-pools \
--ipam-pool-ids ipam-pool-prod123 \
--region ap-south-19. Deallocate CIDR (Cleanup)
aws ec2 deprovision-ipam-pool-cidr \
--ipam-pool-id ipam-pool-prod123 \
--cidr 10.100.0.0/18 \
--region ap-south-110. Delete IPAM Pool
aws ec2 delete-ipam-pool \
--ipam-pool-id ipam-pool-prod123 \
--region ap-south-1Python Automation with boto3
Below is a production-grade Python script for IPAM operations using
boto3 .Prerequisites
pip install boto3 botocoreIPAM Automation Script
#!/usr/bin/env python3
"""
AWS VPC IPAM Production Automation Script
Handles: IPAM creation, pool hierarchy, CIDR allocation, VPC creation, compliance checks
"""
import boto3
import json
import logging
from botocore.exceptions import ClientError
from typing import Optional, Dict, List
# Configure logging
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(levelname)s - %(message)s'
)
logger = logging.getLogger(__name__)
class IPAMManager:
def __init__(self, region: str = 'ap-south-1'):
"""Initialize IPAM manager with boto3 client"""
self.region = region
self.ec2_client = boto3.client('ec2', region_name=region)
self.ram_client = boto3.client('ram', region_name=region)
self.ipam_arn = None
self.pool_ids = {}
def create_ipam(self, operating_regions: List[str], tags: Optional[Dict] = None) -> str:
"""Create IPAM in specified regions"""
try:
region_list = [{'RegionName': r} for r in operating_regions]
params = {
'OperatingRegions': region_list
}
if tags:
tag_spec = [{'Key': k, 'Value': v} for k, v in tags.items()]
params['TagSpecifications'] = [{
'ResourceType': 'ipam',
'Tags': tag_spec
}]
response = self.ec2_client.create_ipam(**params)
self.ipam_arn = response['Ipam']['IpamArn']
logger.info(f"IPAM created: {self.ipam_arn}")
return self.ipam_arn
except ClientError as e:
logger.error(f"Failed to create IPAM: {e}")
raise
def create_pool(self,
pool_name: str,
address_family: str = 'ipv4',
scope: str = 'ipam-scope-0123456789abcdef0', # Pass actual scope ID
locale: str = 'ap-south-1',
description: str = '',
source_pool_ids: Optional[List[str]] = None,
netmask_rules: Optional[Dict] = None,
tags: Optional[Dict] = None) -> str:
"""Create IPAM pool with optional hierarchy and netmask rules"""
if not self.ipam_arn:
raise ValueError("IPAM ARN not set. Call create_ipam() first.")
try:
params = {
'IpamScopeId': scope,
'AddressFamily': address_family,
'Description': description,
'Locale': locale
}
if source_pool_ids:
params['SourceIpamPoolId'] = source_pool_ids[0]
if netmask_rules:
params['AllocationDefaultNetmaskLength'] = netmask_rules.get('default', 18)
params['AllocationMinNetmaskLength'] = netmask_rules.get('min', 18)
params['AllocationMaxNetmaskLength'] = netmask_rules.get('max', 24)
if tags:
tag_spec = [{'Key': k, 'Value': v} for k, v in tags.items()]
params['TagSpecifications'] = [{
'ResourceType': 'ipam-pool',
'Tags': tag_spec
}]
response = self.ec2_client.create_ipam_pool(**params)
pool_id = response['IpamPool']['IpamPoolId']
self.pool_ids[pool_name] = pool_id
logger.info(f"Pool created: {pool_name} ({pool_id})")
return pool_id
except ClientError as e:
logger.error(f"Failed to create pool {pool_name}: {e}")
raise
def allocate_cidr(self,
pool_id: str,
cidr: Optional[str] = None,
netmask_length: Optional[int] = None) -> str:
"""Allocate CIDR from pool (manual or auto)"""
try:
params = {'IpamPoolId': pool_id}
if cidr:
params['Cidr'] = cidr
elif netmask_length:
params['NetmaskLength'] = netmask_length
else:
raise ValueError("Specify either cidr or netmask_length")
response = self.ec2_client.provision_ipam_pool_cidr(**params)
allocated_cidr = response['IpamPoolCidr']['Cidr']
logger.info(f"Allocated CIDR: {allocated_cidr} from pool {pool_id}")
return allocated_cidr
except ClientError as e:
logger.error(f"Failed to allocate CIDR from pool {pool_id}: {e}")
raise
def create_vpc_from_pool(self,
cidr: str,
vpc_name: str,
pool_id: str,
tags: Optional[Dict] = None) -> str:
"""Create VPC using IPAM-allocated CIDR"""
try:
tag_spec = [{
'ResourceType': 'vpc',
'Tags': [
{'Key': 'Name', 'Value': vpc_name},
{'Key': 'IpamPoolId', 'Value': pool_id}
]
}]
if tags:
tag_spec[0]['Tags'].extend([{'Key': k, 'Value': v} for k, v in tags.items()])
response = self.ec2_client.create_vpc(
CidrBlock=cidr,
TagSpecifications=tag_spec
)
vpc_id = response['Vpc']['VpcId']
logger.info(f"VPC created: {vpc_id} with CIDR {cidr}")
return vpc_id
except ClientError as e:
logger.error(f"Failed to create VPC: {e}")
raise
def share_pool_via_ram(self,
pool_id: str,
share_name: str,
principal_arns: List[str]) -> str:
"""Share IPAM pool with OU accounts via AWS RAM"""
try:
# Get pool ARN
pool_arn = f"arn:aws:ec2::{self._get_account_id()}:ipam-pool/{pool_id}"
# Create resource share
response = self.ram_client.create_resource_share(
name=share_name,
resourceArns=[pool_arn],
principals=principal_arns,
allowExternalPrincipals=False
)
share_arn = response['resourceShare']['resourceShareArn']
logger.info(f"RAM share created: {share_arn}")
return share_arn
except ClientError as e:
logger.error(f"Failed to create RAM share: {e}")
raise
def check_compliance(self,
resource_type: str = 'vpc',
compliance_status: Optional[str] = None) -> List[Dict]:
"""Check IPAM compliance for resources"""
if not self.ipam_arn:
raise ValueError("IPAM ARN not set")
try:
# Derive the private scope ID from the IPAM ARN
scopes = self.ec2_client.describe_ipam_scopes(
Filters=[{'Name': 'ipam-arn', 'Values': [self.ipam_arn]},
{'Name': 'ipam-scope-type', 'Values': ['private']}]
)
scope_id = scopes['IpamScopes'][0]['IpamScopeId']
params = {
'IpamScopeId': scope_id,
'Filters': [{'Name': 'resource-type', 'Values': [resource_type]}]
}
if compliance_status:
params['Filters'].append({
'Name': 'compliance-status',
'Values': [compliance_status]
})
response = self.ec2_client.get_ipam_resource_cidrs(**params)
compliance_results = response['IpamResourceCidrs']
logger.info(f"Found {len(compliance_results)} {resource_type} resources")
return compliance_results
except ClientError as e:
logger.error(f"Failed to check compliance: {e}")
raise
def get_pool_utilization(self, pool_id: str) -> Dict:
"""Get pool utilization metrics"""
try:
response = self.ec2_client.describe_ipam_pools(
IpamPoolIds=[pool_id]
)
pool_info = response['IpamPools'][0]
utilization = {
'pool_id': pool_id,
'address_family': pool_info['AddressFamily'],
'locale': pool_info['Locale'],
'allocation_default_netmask_length': pool_info.get('AllocationDefaultNetmaskLength'),
'state': pool_info['State']
}
logger.info(f"Pool utilization: {utilization}")
return utilization
except ClientError as e:
logger.error(f"Failed to get pool utilization: {e}")
raise
def deallocate_cidr(self, pool_id: str, cidr: str) -> bool:
"""Deallocate CIDR from pool (cleanup)"""
try:
self.ec2_client.deprovision_ipam_pool_cidr(
IpamPoolId=pool_id,
Cidr=cidr
)
logger.info(f"Deallocated CIDR: {cidr} from pool {pool_id}")
return True
except ClientError as e:
logger.error(f"Failed to deallocate CIDR: {e}")
raise
def _get_account_id(self) -> str:
"""Get current AWS account ID"""
sts = boto3.client('sts')
return sts.get_caller_identity()['Account']
def main():
"""Production workflow: Create IPAM → Pools → Allocate CIDR → Create VPC"""
# Initialize manager
ipam_mgr = IPAMManager(region='ap-south-1')
# 1. Create IPAM
ipam_arn = ipam_mgr.create_ipam(
operating_regions=['ap-south-1', 'us-east-1'],
tags={'Name': 'Production-IPAM', 'Environment': 'Production', 'ManagedBy': 'Python'}
)
print(f"IPAM ARN: {ipam_arn}")
# 2. Create Top-Level Pool
global_pool_id = ipam_mgr.create_pool(
pool_name='Global-Private-Pool',
address_family='ipv4',
scope='private',
locale='ap-south-1',
description='Top-level private IP pool',
tags={'Name': 'Global-Private-Pool', 'Environment': 'Production'}
)
# 3. Create Regional Pool with Netmask Rules
regional_pool_id = ipam_mgr.create_pool(
pool_name='AP-South-1-Regional-Pool',
address_family='ipv4',
scope='private',
locale='ap-south-1',
description='Private pool for ap-south-1',
source_pool_ids=[global_pool_id],
netmask_rules={'default': 18, 'min': 18, 'max': 24},
tags={'Name': 'AP-South-1-Regional-Pool', 'Region': 'ap-south-1'}
)
# 4. Create Production Environment Pool
prod_pool_id = ipam_mgr.create_pool(
pool_name='Production-Environment-Pool',
address_family='ipv4',
scope='private',
locale='ap-south-1',
description='Production VPC pool',
source_pool_ids=[regional_pool_id],
netmask_rules={'default': 18, 'min': 18, 'max': 18},
tags={'Name': 'Production-Environment-Pool', 'CostCenter': '12345'}
)
# 5. Allocate CIDR (auto-allocate with /18)
allocated_cidr = ipam_mgr.allocate_cidr(
pool_id=prod_pool_id,
netmask_length=18
)
print(f"Allocated CIDR: {allocated_cidr}")
# 6. Create VPC from allocated CIDR
vpc_id = ipam_mgr.create_vpc_from_pool(
cidr=allocated_cidr,
vpc_name='Production-VPC-1',
pool_id=prod_pool_id,
tags={'Environment': 'Production', 'Application': 'E-Commerce'}
)
print(f"VPC ID: {vpc_id}")
# 7. Share Pool via RAM
ou_principal = 'arn:aws:organizations::123456789012:ou/o-abc123/ou-xyz789'
share_arn = ipam_mgr.share_pool_via_ram(
pool_id=prod_pool_id,
share_name='IPAM-Pool-Share-Production',
principal_arns=[ou_principal]
)
print(f"RAM Share ARN: {share_arn}")
# 8. Check Compliance
compliance = ipam_mgr.check_compliance(resource_type='vpc')
print(f"Compliance check results: {len(compliance)} VPCs")
for resource in compliance:
print(f" - {resource['ResourceId']}: {resource['ComplianceStatus']}")
# 9. Get Pool Utilization
utilization = ipam_mgr.get_pool_utilization(prod_pool_id)
print(f"Pool utilization: {json.dumps(utilization, indent=2)}")
# Cleanup example (comment out in production)
# ipam_mgr.deallocate_cidr(prod_pool_id, allocated_cidr)
# print("Deallocated CIDR for cleanup")
if __name__ == '__main__':
main()Running the Script
# Set AWS credentials
export AWS_PROFILE=production-network-account
export AWS_REGION=ap-south-1
# Run script
python3 ipam_automation.pyOutput:
2026-07-23 12:00:00 - INFO - IPAM created: arn:aws:ec2::123456789012:ipam/ipam-abc123
IPAM ARN: arn:aws:ec2::123456789012:ipam/ipam-abc123
2026-07-23 12:00:05 - INFO - Pool created: Global-Private-Pool (ipam-pool-xyz1)
2026-07-23 12:00:10 - INFO - Pool created: AP-South-1-Regional-Pool (ipam-pool-xyz2)
2026-07-23 12:00:15 - INFO - Pool created: Production-Environment-Pool (ipam-pool-prod123)
Allocated CIDR: 10.100.0.0/18
2026-07-23 12:00:20 - INFO - VPC created: vpc-abc123 with CIDR 10.100.0.0/18
VPC ID: vpc-abc123
2026-07-23 12:00:25 - INFO - RAM share created: arn:aws:ram:ap-south-1:123456789012:resource-share/xyz789
RAM Share ARN: arn:aws:ram:ap-south-1:123456789012:resource-share/xyz789
Compliance check results: 1 VPCs
- vpc-abc123: compliant
Pool utilization: {
"pool_id": "ipam-pool-prod123",
"address_family": "ipv4",
"locale": "ap-south-1",
"allocation_default_netmask_length": 18,
"state": "create-complete"
}Advanced Production Scenarios
1. Multi-Account VPC Creation from Shared Pool
After sharing the pool via RAM, member accounts can create VPCs:
# In member account (with RAM share accepted)
import boto3
ec2 = boto3.client('ec2', region_name='ap-south-1')
# Create VPC directly from shared pool (CIDR auto-allocated)
response = ec2.create_vpc(
Ipv4IpamPoolId='ipam-pool-prod123', # Shared pool ID
Ipv4NetmaskLength=18
)
print(f"VPC created: {response['Vpc']['VpcId']}")2. BYOIP Integration (Bring Your Own Public IPs)
For enterprises using their own public IP space:
# 1. Create a Route Origin Authorization (ROA) at your RIR (ARIN/RIPE/APNIC)
# for your CIDR pointing to your AWS account ASN (16509 or 14618).
# Then generate a signed authorization message and provide it below.
# 2. Provision public CIDR to IPAM
aws ec2 provision-byoip-cidr \
--cidr 203.0.113.0/24 \
--cidr-authorization-context "{\"Message\":\"...\",\"Signature\":\"...\"}" \
--region ap-south-1
# 3. Advertise CIDR (make it usable)
aws ec2 advertise-byoip-cidr \
--cidr 203.0.113.0/24 \
--region ap-south-1
# 4. Allocate from BYOIP pool for ALB/CloudFront
aws ec2 provision-ipam-pool-cidr \
--ipam-pool-id ipam-pool-public-123 \
--cidr 203.0.113.0/243. Automated Compliance Monitoring with Lambda
# lambda_ipam_compliance.py
import boto3
import json
def lambda_handler(event, context):
ec2 = boto3.client('ec2')
sns = boto3.client('sns')
ipam_arn = 'arn:aws:ec2::123456789012:ipam/ipam-abc123'
# Get private scope ID
scopes = ec2.describe_ipam_scopes(
Filters=[{'Name': 'ipam-arn', 'Values': [ipam_arn]},
{'Name': 'ipam-scope-type', 'Values': ['private']}]
)
scope_id = scopes['IpamScopes'][0]['IpamScopeId']
# Check compliance
response = ec2.get_ipam_resource_cidrs(
IpamScopeId=scope_id,
Filters=[{'Name': 'compliance-status', 'Values': ['noncompliant']}]
)
non_compliant = response['IpamResourceCidrs']
if non_compliant:
# Send SNS alert
message = {
'alert': 'Non-compliant IPAM resources detected',
'count': len(non_compliant),
'resources': [r['ResourceId'] for r in non_compliant]
}
sns.publish(
TopicArn='arn:aws:sns:ap-south-1:123456789012:IPAM-Compliance-Alerts',
Message=json.dumps(message),
Subject='IPAM Compliance Alert'
)
return {
'statusCode': 200,
'body': json.dumps(f'Checked {len(non_compliant)} non-compliant resources')
}Terraform for Lambda + EventBridge:
resource "aws_lambda_function" "ipam_compliance_checker" {
filename = "lambda_ipam_compliance.zip"
function_name = "IPAM-Compliance-Checker"
role = aws_iam_role.lambda_role.arn
handler = "lambda_ipam_compliance.lambda_handler"
runtime = "python3.9"
timeout = 30
environment {
variables = {
IPAM_ARN = aws_vpc_ipam.production_ipam.arn
}
}
}
resource "aws_cloudwatch_event_rule" "ipam_compliance_schedule" {
name = "IPAM-Compliance-Check"
schedule_expression = "rate(1 hour)" # Check every hour
}
resource "aws_cloudwatch_event_target" "invoke_lambda" {
rule = aws_cloudwatch_event_rule.ipam_compliance_schedule.name
target_id = "IPAMComplianceLambda"
arn = aws_lambda_function.ipam_compliance_checker.arn
}4. Cost Optimization with IPAM Tagging
Use IPAM pool tags for cost allocation:
# Tag pools for cost tracking
tags = {
'CostCenter': '12345',
'Application': 'E-Commerce-Platform',
'Team': 'Infrastructure',
'Environment': 'Production'
}
ipam_mgr.create_pool(
pool_name='Production-Pool',
# ... other params
tags=tags
)Then use AWS Cost Explorer with these tags to track IP-related costs by pool, team, or application.
Migration Strategy: From Manual to IPAM
For existing environments without IPAM:
Phase 1: Discovery and Planning
# 1. Export all existing VPC CIDRs
aws ec2 describe-vpcs \
--query 'Vpcs[*].[VpcId,CidrBlock,Tags[?Key==`Name`].Value]' \
--output table
# 2. Check for overlaps (use Python script or AWS Config)
# 3. Document current IP usage per account/regionPhase 2: IPAM Setup
- Create IPAM in network account
- Build pool hierarchy matching current structure
- Import existing CIDRs as "manual allocations" (no auto-allocate)
Phase 3: Enforce IPAM for New VPCs
- Update CI/CD pipelines to use IPAM pool IDs
- Implement SCPs to block non-IPAM VPC creation
- Train teams on IPAM-based Terraform/CLI workflows
Phase 4: Gradual Migration
- Migrate non-production VPCs first
- Reallocate CIDRs from IPAM pools
- Decommission old VPCs after validation
- Repeat for production (with change management)
Common Pitfalls and Troubleshooting
1. "CIDR overlaps with existing VPC"
Cause: IPAM pool doesn't include existing CIDRs.
Fix:
# Import existing CIDR as manual allocation
aws ec2 provision-ipam-pool-cidr \
--ipam-pool-id ipam-pool-prod123 \
--cidr 10.100.0.0/18 \
--region ap-south-12. "Pool not shared with this account"
Fix: Ensure RAM share is accepted:
# In member account
aws ram list-received-invitations
aws ram accept-resource-share-invitation --resource-share-arn arn:aws:ram:...3. "Netmask length not allowed"
Fix: Adjust pool netmask rules or use correct netmask:
# Check pool rules
aws ec2 describe-ipam-pools \
--ipam-pool-ids ipam-pool-prod123 \
--query 'IpamPools.[AllocationDefaultNetmaskLength,AllocationMinNetmaskLength,AllocationMaxNetmaskLength]'4. "Resource not compliant"
Cause: VPC created outside IPAM or wrong netmask.
Fix: Recreate VPC from IPAM pool or delete and re-allocate CIDR.
Performance and Limits
IPAM Limits (as of 2026)
- IPAMs per region: 1 per account
- Pools per IPAM: 100 (default), can increase via support
- Pool depth: 10 levels
- CIDR allocations per pool: 1,000
- VPCs per IPAM: 10,000
Monitoring IPAM Health
# IPAM does not publish metrics to CloudWatch.
# Use get_ipam_resource_cidrs to monitor pool utilization and compliance.
import boto3
ec2 = boto3.client('ec2', region_name='ap-south-1')
# Get private scope ID
scopes = ec2.describe_ipam_scopes(
Filters=[{'Name': 'ipam-arn', 'Values': [ipam_arn]},
{'Name': 'ipam-scope-type', 'Values': ['private']}]
)
scope_id = scopes['IpamScopes'][0]['IpamScopeId']
# List all resource CIDRs and their compliance status
response = ec2.get_ipam_resource_cidrs(
IpamScopeId=scope_id,
Filters=[{'Name': 'compliance-status', 'Values': ['noncompliant']}]
)
non_compliant = response['IpamResourceCidrs']
print(f"Non-compliant resources: {len(non_compliant)}")Conclusion
AWS VPC IPAM is essential for production environments managing IP addresses at scale. By implementing hierarchical pools, enforcing netmask rules, automating with IaC/CLI/Python, and monitoring compliance, you can eliminate CIDR overlaps, reduce manual errors, and enable multi-account growth.
Start with a pilot in non-production, refine your pool hierarchy, then enforce IPAM across all accounts using RAM shares and SCPs. Your future self (and network team) will thank you.
References:
Enjoyed reading this content? Let the author know!
Your likes, comments, shares, and saves help creators reach more builders.
Loading recommendations
Loading article