chriz
chriz

Reputation: 1896

How to run a Google Cloud Build trigger via cli / rest api / cloud functions?

Is there such an option? My use case would be running a trigger for a production build (deploys to production). Ideally, that trigger doesn't need to listen to any change since it is invoked manually via chatbot.

I saw this video CI/CD for Hybrid and Multi-Cloud Customers (Cloud Next '18) announcing there's an API trigger support, I'm not sure if that's what I need.

Upvotes: 11

Views: 12422

Answers (9)

Borislav Gizdov
Borislav Gizdov

Reputation: 1930

You can execute a trigger from a specific project and branch with this command:

gcloud --project=my-project builds triggers run my-build-trigger --branch master

To check the latest build statuses:

gcloud --project=my-project builds list | head

Upvotes: 2

Mauricio
Mauricio

Reputation: 621

Try this and see available options:

$ gcloud builds triggers run --help

Upvotes: 1

bajaco
bajaco

Reputation: 980

I was in search of the same thing (Fall 2022) and while I haven't tested yet I wanted to answer before I forget. It appears to be available now in gcloud beta builds triggers run TRIGGER

Upvotes: 0

Tobias Ernst
Tobias Ernst

Reputation: 4634

You can use google client api to create build jobs with python:

import operator
from functools import reduce
from typing import Dict, List, Union

from google.oauth2 import service_account
from googleapiclient import discovery


class GcloudService():
    def __init__(self, service_token_path, project_id: Union[str, None]):
        self.project_id = project_id
        self.service_token_path = service_token_path
        self.credentials = service_account.Credentials.from_service_account_file(self.service_token_path)


class CloudBuildApiService(GcloudService):
    def __init__(self, *args, **kwargs):
        super(CloudBuildApiService, self).__init__(*args, **kwargs)

        scoped_credentials = self.credentials.with_scopes(['https://www.googleapis.com/auth/cloud-platform'])
        self.service = discovery.build('cloudbuild', 'v1', credentials=scoped_credentials, cache_discovery=False)

    def get(self, build_id: str) -> Dict:
        return self.service.projects().builds().get(projectId=self.project_id, id=build_id).execute()

    def create(self, image_name: str, gcs_name: str, gcs_path: str, env: Dict = None):
        args: List[str] = self._get_env(env) if env else []
        opt_params: List[str] = [
            '-t', f'gcr.io/{self.project_id}/{image_name}',
            '-f', f'./{image_name}/Dockerfile',
            f'./{image_name}'
        ]
        build_cmd: List[str] = ['build'] + args + opt_params
        body = {
            "projectId": self.project_id,
            "source": {
                'storageSource': {
                    'bucket': gcs_name,
                    'object': gcs_path,
                }
            },
            "steps": [
                {
                    "name": "gcr.io/cloud-builders/docker",
                    "args": build_cmd,
                },
            ],
            "images": [
                [
                    f'gcr.io/{self.project_id}/{image_name}'
                ]
            ],
        }
        return self.service.projects().builds().create(projectId=self.project_id, body=body).execute()

    def _get_env(self, env: Dict) -> List[str]:
        env: List[str] = [['--build-arg', f'{key}={value}'] for key, value in env.items()]
        # Flatten array
        return reduce(operator.iconcat, env, [])

Here is the documentation so that you can implement more functionality: https://cloud.google.com/cloud-build/docs/api

Hope this helps.

Upvotes: 2

Chris Stryczynski
Chris Stryczynski

Reputation: 33861

This now seems to be possible via API:

https://cloud.google.com/cloud-build/docs/api/reference/rest/v1/projects.triggers/run

request.json:

{
  "projectId": "*****",
  "commitSha": "************"
}

curl request (with using a gcloud command):

PROJECT_ID="********" TRIGGER_ID="*******************"; curl -X POST -T request.json -H "Authorization: Bearer $(gcloud config config-helper \
    --format='value(credential.access_token)')" \
    https://cloudbuild.googleapis.com/v1/projects/"$PROJECT_ID"/triggers/"$TRIGGER_ID":run

Upvotes: 5

Mithrill
Mithrill

Reputation: 303

You should be able to manually trigger a build using curl and a json payload. For details see: https://cloud.google.com/cloud-build/docs/running-builds/start-build-manually#running_builds.

Given that, you could write a Python Cloud function to replicate the curl call via the requests module.

Upvotes: 0

manikantanr
manikantanr

Reputation: 574

I did same thing few days ago.

You can submit your builds using gcloud and rest api

gcloud:

gcloud builds submit --no-source  --config=cloudbuild.yaml --async --format=json

Rest API:

Send you cloudbuild.yaml as JSON with Auth Token to this url https://cloudbuild.googleapis.com/v1/projects/standf-188123/builds?alt=json

example cloudbuild.yaml:

steps:

- name: 'gcr.io/cloud-builders/docker'
  id: Docker Version
  args: ["version"]

- name: 'alpine'
  id:  Hello Cloud Build
  args: ["echo", "Hello Cloud Build"]

example rest_json_body:

{"steps": [{"args": ["version"], "id": "Docker Version", "name": "gcr.io/cloud-builders/docker"}, {"args": ["echo", "Hello Cloud Build"], "id": "Hello Cloud Build", "name": "alpine"}]}

Upvotes: 8

Doug Stevenson
Doug Stevenson

Reputation: 317302

If you just want to create a function that you can invoke directly, you have two choices:

  1. An HTTP trigger with a standard API endpoint
  2. A pubsub trigger that you invoke by sending a message to a pubsub topic

The first is the more common approach, as you are effectively creating a web API that any client can call with an HTTP library of their choice.

Upvotes: 1

Dan
Dan

Reputation: 224

you can trigger a function via

gcloud functions call NAME --data 'THING'

inside your function you can do pretty much anything possibile within Googles Public API's

if you just want to directly trigger Google Cloud Builder from git then its probably advisable to use Release version tags - so your chatbot might add a release tag to your release branch in git at which point cloud-builder will start the build.

more info here https://cloud.google.com/cloud-build/docs/running-builds/automate-builds

Upvotes: -1

Related Questions