In AWS, I have a centralized networking account that defines all the VPCs and subnets. And each VPC is shared with target accounts using Resource Access Manager (RAM). Given an IP, need to find out the target account ID with which the VPC/subnet has been shared with. Here is what I have done so far:
In the code below, vpc
parameter contains the vpc lookup response and and ip_addr
is the IP address we are looking for
def lookup_ipaddr (session, ec2_client, vpc, ip_addr): found = False if (ipaddress.ip_address(ip_addr) in ipaddress.ip_network(vpc['CidrBlock'])): filters = [{'Name':'vpc-id', 'Values':[ vpc['VpcId'] ]}] subnets = ec2_client.describe_subnets( Filters = filters )['Subnets'] for subnet in subnets: if (ipaddress.ip_address(ip_addr) in ipaddress.ip_network(subnet['CidrBlock'])): found = True tags = subnet['Tags'] # tags returned by previous api is in different form than that required by RAM for tag in tags: tag['tagKey'] = tag['Key'] tag['tagValues'] = [tag['Value']] del tag['Key'] del tag['Value'] print("nn") print (tags) print("nn") resourceArn = subnet['SubnetArn'] ram_client = session.client('ram') resp = ram_client.get_resource_shares (resourceOwner = 'SELF', tagFilters=tags)
However the API call get_resource_shares
doesn’t return any response (except Response Metadata). Any suggestion on how to find out the destination account ID/Principal with which the subnet was shared?
Advertisement
Answer
After a bit of digging, I was able to obtain the destination account id by using list_principals
api of AWS Resource Access Manager (RAM): https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/ram.html#RAM.Client.list_principals
Here is the full python code:
def lookup_ipaddr (session, ec2_client, vpc, ip_addr): found = False filters = [{'Name':'vpc-id', 'Values':[ vpc['VpcId'] ]}] subnets = ec2_client.describe_subnets( Filters = filters )['Subnets'] for subnet in subnets: if (ipaddress.ip_address(ip_addr) in ipaddress.ip_network(subnet['CidrBlock'])): resourceArn = subnet['SubnetArn'] ram_client = session.client('ram') resp = ram_client.list_principals( resourceOwner = 'SELF', resourceArn = resourceArn ) print(f"Subnet {subnet['SubnetId']} is shared with account [{resp['principals'][0]['id']}]") found = True break return found