'How to list the vpc firewall rules in GCP using python sdk?

I am trying to generate a report that gives info about the vpc, source ranges, ip protocol and ports and the targets that the firewall rule is applied to.. for example if the rule is applied to a VM, i also want to grab the vm name, the subnetwork it is in etc..

I am using this method:firewalls.list, which is giving me the source range, IP Protocol & port, VPC name, but i also want to include the subnetwork name and the target resources the rule is applied to...

import requests
import json
import re
import sys
import subprocess
import os
from googleapiclient import discovery
from oauth2client.client import GoogleCredentials
from google.oauth2 import service_account


credentials = service_account.Credentials.from_service_account_file("")
service = discovery.build('cloudresourcemanager', 'v1', credentials=credentials)
request = service.projects().list()
token1 = subprocess.Popen("gcloud auth print-access-token", stdout=subprocess.PIPE, shell = True)
token, error = token1.communicate()
token = str(token.decode("utf-8"))
token = token.rstrip("\n")
token = token.rstrip("\r")

while request is not None:
    response = request.execute()
    for project in response.get('projects', []):
        projectid = project['projectId']
        projectname = project['name']

        headers = {
        'Authorization': 'Bearer ' + token,
        'x-goog-user-project': projectid
        }

        try:
            get_url = "https://compute.googleapis.com/compute/v1/projects/"+ projectid +"/global/firewalls"
            get_url_data = requests.get(get_url, headers= headers)
            get_api2_json = json.loads(get_url_data.text)
            for vpc in get_api2_json["items"]:
                vpcname = vpc["network"]
                vpcname = vpcname.split("/")[-1]
                rulename = vpc["name"]
                direction = vpc["direction"]
                sourcerange = vpc["sourceRanges"]
                port = vpc["allowed"]["IPProtocol"]

    request = service.projects().list_next(previous_request=request, previous_response=response)

From this i am able to get vpc name, rule, direction, port .... How can i get subnetwork, target resources that this rule applies (i.e name of resource and subnetwork associated etc)?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source