2
votes

I am using Python to interact with Google Compute Engine. I am able to create/stop machines using Python directly. I have used sample code from GoogleCloudPlatform for this purpose and it is working fine.

Now I want to open some ports to interact with machine from outside world using the Python API.

This related question already tells how to open a specific port from Google console web and gcloud command, so my question is specifically how to do it with the Python API.

1
While I'm no Python guru, it might be worth checking out the API explorer to see how to construct API calls for inserting firewall rules here developers.google.com/apis-explorer/#search/firewall/m/compute/… and the API call to delete firewall rules here developers.google.com/apis-explorer/#search/firewall/m/compute/… . There is also the google-api-python-client which may also be helpful github.com/google/google-api-python-client .neilH

1 Answers

2
votes

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)