Created
November 28, 2022 15:07
-
-
Save cosimo/0bbe6d1a6afad124944c87ea123a8aac to your computer and use it in GitHub Desktop.
How to list Google Cloud NAT ips for a project
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python3 | |
# encoding: utf-8 | |
""" | |
Lists all the GCP CloudNat IP addresses in a list of projects | |
Usage: | |
./gcp-list-nat-ips.py --project <gcp-project-name> | |
""" | |
import click | |
from typing import List | |
from google.cloud.compute_v1.services.routers import RoutersClient | |
from google.cloud.compute_v1.services.addresses import AddressesClient | |
from google.cloud.compute_v1.types import compute, Address, Router, RouterNat | |
# from google.oauth2 import service_account | |
def get_addresses(project: str) -> list: | |
client = AddressesClient() | |
request = compute.AggregatedListAddressesRequest(project=project) | |
response = client.aggregated_list(request, timeout=5.0) | |
results_list = list() | |
for zone, addresses_list in response: | |
if len(addresses_list.addresses) > 0: | |
for address in addresses_list.addresses: | |
results_list.append((address.self_link, address,)) | |
return results_list | |
def get_routers(project: str) -> list: | |
client = RoutersClient() | |
request = compute.AggregatedListRoutersRequest(project=project) | |
response = client.aggregated_list(request, timeout=5.0) | |
results_list = list() | |
for zone, routers_list in response: | |
if len(routers_list.routers) > 0: | |
for router in routers_list.routers: | |
results_list.append((zone, router.name, router,)) | |
return results_list | |
def get_router_nat_ips(router: Router) -> list: | |
nats: List[RouterNat] = router.nats | |
ips = list() | |
for nat in nats: | |
ips.extend(nat.nat_ips) | |
return ips | |
def to_dict(l: list) -> dict: | |
result_dict = dict() | |
for k, v in l: | |
if k in result_dict: | |
raise KeyError(f"Would overwrite existing value for {k}") | |
result_dict[k] = v | |
return result_dict | |
@click.command() | |
@click.option("--project", "-p", required=True, multiple=True) | |
def main(**options): | |
for project in options["project"]: | |
project_routers = get_routers(project) | |
if not project_routers: | |
continue | |
project_addresses = to_dict(get_addresses(project)) | |
for zone, name, router in project_routers: | |
nat_ips = get_router_nat_ips(router) | |
for ip in nat_ips: | |
resolved = project_addresses[ip] | |
print("\t".join(( | |
project, | |
zone, | |
router.name, | |
router.description, | |
resolved.address, | |
resolved.description, | |
))) | |
if __name__ == "__main__": | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment