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
Hello @snef,
You can try the following troubleshooting options:
Let me know if it helped, thanks!