pythongoogle-cloud-platformgoogle-api-python-clientgoogle-cloud-buildgoogle-cloud-python

How to use python-cloudbuild to run a build trigger


How to use python-cloudbuild library to run a build trigger with correctly passing data from SourceRepo?

UPDATE 1:

I have a build trigger set up and I am trying to run that trigger by changing the substitutions and the repo branch

UPDATE 2:

Actual code result:

Traceback (most recent call last): File "/layers/google.python.pip/pip/lib/python3.9/site-packages/google/api_core/grpc_helpers.py", line 67, in error_remapped_callable return callable_(*args, **kwargs) File "/layers/google.python.pip/pip/lib/python3.9/site-packages/grpc/_channel.py", line 946, in call return _end_unary_response_blocking(state, call, False, None) File "/layers/google.python.pip/pip/lib/python3.9/site-packages/grpc/_channel.py", line 849, in _end_unary_response_blocking raise _InactiveRpcError(state) grpc._channel._InactiveRpcError: <_InactiveRpcError of RPC that terminated with: status = StatusCode.INTERNAL

credentials, project_id = google.auth.default()
client = cloudbuild_v1.services.cloud_build.CloudBuildClient()

trigger_id = '2f1erbc4-asdf-1234-qwery-c4bc74d16d62'

repo_source = cloudbuild_v1.RepoSource()
repo_source.branch_name = 'develop'
repo_source.substitutions = {
    "_ENVIRONMENT":"dev",
    "NAMESPACE":"dev"
}

operation = client.run_build_trigger(
    project_id=project_id,
    trigger_id=trigger_id,
    source=repo_source
)

Solution

  • I am facing the same issue when using the Cloud Build Client Library for Python (google-cloud-build). However, it does work properly when calling the REST API directly, so the library seems to be at cause here. As an alternative, you can achieve the same using the Google API Python client library (google-api-python-client):

    from googleapiclient.discovery import build
    
    project_id = "my-project-id"
    trigger_id = "00000000-1111-2222-aaaa-bbbbccccdddd"
    
    with build("cloudbuild", "v1") as cloudbuild:
      run_build_trigger = cloudbuild.projects().triggers().run(
        projectId = project_id,
        triggerId = trigger_id,
        body = {
          "branchName": "dev",
          "substitutions": {
            "_TEST": "FOO"
          }
        }
      )
    
      run_build_trigger.execute()
    

    Make sure that all substitutions are already declared on the existing trigger.