Here's some sample code to get you started, but I recommend you review the entire firewalls portion of the compute API to make sure you use all the options you need:
This runs successfully on cloud shell, which uses application default credentials. You might need to authenticate in a different way.
import googleapiclient.discovery
if __name__ == '__main__':
MY_PROJECT = 'your-project-name'
# Get the firewalls resource
firewalls = googleapiclient.discovery.build('compute', 'v1').firewalls()
# Build the REST parameters for a port 9090 ingress allow-all firewall.
firewall_definition = {
"name": "default-allow-9090",
"direction": "INGRESS",
# targetTags: "add tags here if you need them -- default is apply to all",
"sourceRanges" : "0.0.0.0/0",
"allowed": { "IPProtocol": "tcp", "ports": [ 9090 ] },
"priority": 1000,
"network": "https://www.googleapis.com/compute/v1/projects/%s/global/networks/default" % MY_PROJECT,
}
# Execute the call.
result = firewalls.insert(project=MY_PROJECT, body=firewall_definition).execute()
# View Response
print(result)