Search code examples
pythongoogle-compute-enginegoogle-apis-explorer

HttpError 503, while creating subnet using GCP Python API


Hello Everyone, Need your thoughts on an issue I am getting with a python script to create vpc and subnet.

My script is working fine when creating vpc, but next step of subnet creation is failing with error

googleapiclient.errors.HttpError: <HttpError 503 when requesting https://www.googleapis.com/compute/v1/projects/<projectname>/regions/us-east1/subnetworks?alt=json returned "Internal error. Please try again or contact Google Support.

I am able to create subnet from UI and from rest API page.

Here is the script code I am using for subnet creation-

def create_subnet(compute, project, region, classname):

    subnetname = classname
    networkpath = 'projects/<projectname>/global/networks/%s' % (classname)
    ipCidrRange = "10.0.0.0/16"

    config = {
  "name": subnetname,
  "network": networkpath,
  "ipCidrRange": ipCidrRange
}

    print('##### Print Config ##### %s' % (config))

    return compute.subnetworks().insert(
        project=project,
        region=region,
        body=config).execute()
    ```

def main(project, classname, zone, region):

compute = googleapiclient.discovery.build('compute', 'v1')

print('Creating vpc')

operation = create_vpc(compute, project, classname)

print('Creating subnet')

operation = create_subnet(compute, project, region, classname)
```

Thanks in advance for comments and suggestions.


Solution

  • I got the root cause of this issue. I was making subnet call without waiting for vpc create operation to complete.

    Created new function to wait and call it after vpc creation step resolves the issue.

    def wait_for_global_operation(compute, project, operation):
        print('Waiting for operation to finish...')
        while True:
            result = compute.globalOperations().get(
                project=project,
                operation=operation).execute()
    
            if result['status'] == 'DONE':
                print("done.")
                if 'error' in result:
                    raise Exception(result['error'])
                return result
    
            time.sleep(1)
    

    Thanks Lozano for your comments and feedback.