Google Cloud Scheduler permission error

Hello,

i'm trying to write a python function to create dynamically a trigger schedule on cloud run job using scheduler admin api.

I have implemented this code:

 

 

import requests
from google.oauth2 import service_account
import google.auth.transport.requests

class BearerAuth(requests.auth.AuthBase):
    def __init__(self, token):
        self.token = token
    def __call__(self, r):
        r.headers["authorization"] = "Bearer " + self.token
        return r

def get_token():
    credentials = service_account.Credentials.from_service_account_file(
        "KEY/key.json", scopes=['https://www.googleapis.com/auth/cloud-platform']
    )
    request = google.auth.transport.requests.Request()
    credentials.refresh(request)
    print(credentials.token)

    return credentials.token

def create_scheduler_job(project_id, region, job_name, schedule, uri, sa_email, sa_key_file):
    base_url = "https://cloudscheduler.googleapis.com/v1/projects"
    url = f"{base_url}/{project_id}/locations/{region}/jobs"

    
    headers = {
        'Authorization': f'Bearer {0}'.format(get_token()),
        'Content-Type': 'application/json'
    }

    body = {
        "name": f"projects/{project_id}/locations/{region}/jobs/{job_name}",
        "schedule": schedule,
        "httpTarget": {
            "uri": uri,
            "httpMethod": "POST",
            "oidcToken": {
                "serviceAccountEmail": sa_email
            }
        }
    }

    response = requests.post(url, headers=headers, json=body)

    if response.status_code == 200:
        print('Successfully created job')
    else:
        print('Failed to create job:', response.text)

schedul = create_scheduler_job(
    project_id='my_project_id', 
    region='us-central1', 
    job_name='test-job', 
    schedule='*/5 * * * *', 
    uri='https://us-central1-run.googleapis.com/v2/projects/<my_project_id>/locations/us-central1/jobs/test-job:run', 
    sa_email='project@project-name.iam.gserviceaccount.com',
    sa_key_file=r'C:\path\KEY\key.json')


print(schedul)

 

 

The token is generated but i have this error:

 

 

Failed to create job: {
  "error": {
    "code": 401,
    "message": "Request had invalid authentication credentials. Expected OAuth 2 access token, login cookie or other valid authentication credential. See https://developers.google.com/identity/sign-in/web/devconsole-project.",
    "status": "UNAUTHENTICATED"
  }
}

 

 

How i can fix it? Any help?

Thanks

0 1 337
1 REPLY 1

Hello @snef,

You can try the following troubleshooting options:

  1. It seems that the generated token is what's causing the error. The reason can be your application default credentials are not yet set.
    Set it up by running the gcloud auth application-default login command. You can then check it by using the gcloud auth application-default print-access-token command.
    You should also take a look at this Overflow Post as you might have the same problem. 
  2. Double check if the create_scheduler_job contains the right information. If in line 55, projects/<my_project_id>/locations is not deliberate, then you should probably look into that.
  3. You can also get in touch with Google Cloud Support if the above options don't work.

Let me know if it helped, thanks!