简体   繁体   中英

how to get locationId in Google App Engine not using terminal

To use scheduler_v1.CloudSchedulerClient().location_path() in Python I need parent with projectId and LocationId. I know how to get projectId in code and locationId from terminal, but how to do it in my code?

I've tried to check this website( https://cloud.google.com/functions/docs/reference/rpc/google.cloud.location ), but there are no examples, idk what to do with it

from google.cloud import scheduler_v1


from google.oauth2 import service_account

credentials = service_account.Credentials.from_service_account_file('/home/myname/folder/service_account.json')
service = googleapiclient.discovery.build('cloudresourcemanager', 'v1', credentials = credentials)
request = service.projects().list()
response = request.execute()
client = scheduler_v1.CloudSchedulerClient()

for project in response['projects']:
    parent = client.location_path(project['projectId'], ['LocationID'])
    for element in client.list_jobs(parent):
        print(element)

Thank you!

It is not necessary to use cloudresourcemanager to get the project ID, instead you can use the App Engine environment variable GOOGLE_CLOUD_PROJECT

You can use App engine admin API to get the location ID please check this code snippet.

    credentials = GoogleCredentials.get_application_default()
    #start discovery service and use appengine admin API
    service = discovery.build('appengine', 'v1', credentials=credentials, cache_discovery=False)

    #disable cache for app engine std (avoid noise in logs)
    logging.getLogger('googleapiclient.discovery_cache').setLevel(logging.ERROR)

    #take the project ID form the environment variables
    project = os.environ['GOOGLE_CLOUD_PROJECT']

    #get App engine application details
    req = service.apps().get(appsId=project)

    response =req.execute()

    #this is the application location id
    location_id = (response["locationId"])

I've recently begun using the http://metadata.google.internal/computeMetadata/v1/instance/region endpoint. While it works in App Engine, it's not explicitly documented right now (but it is documented for Cloud Run: https://cloud.google.com/run/docs/reference/container-contract ).

The result from that endpoint will be something that looks like this:

projects/12345678901234/regions/us-central1

Obviously, the region is the last part ( us-central1 ).

Here's a sample that I have in Go (remember to set the Metadata-Flavor header to Google ):

var region string
{
    domain := "http://metadata.google.internal"
    path := "computeMetadata/v1/instance/region"

    request, err := http.NewRequest(http.MethodGet, domain+"/"+path, nil)
    if err != nil {
        logrus.Errorf("Could not create request: %v", err)
        panic(err)
    }
    request.Header.Set("Metadata-Flavor", "Google")
    response, err := http.DefaultClient.Do(request)
    if err != nil {
        logrus.Errorf("Could not perform request: %v", err)
        panic(err)
    }
    contents, err := ioutil.ReadAll(response.Body)
    if err != nil {
        logrus.Errorf("Could not read contents: %v", err)
        panic(err)
    }
    originalRegion := string(contents)
    logrus.Infof("Contents of %q: %s", path, originalRegion)
    parts := strings.Split(originalRegion, "/")
    if len(parts) > 0 {
        region = parts[len(parts)-1]
    }
}
logrus.Infof("Region: %s", region)

In Google App Engine, there are some environment variables set by runtime environment. You can get it by os.environ.get(environment_name).

https://cloud.google.com/appengine/docs/standard/python3/runtime#environment_variables

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM