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

前端 未结 6 1138
野性不改
野性不改 2021-02-09 01:53

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

6条回答
  •  庸人自扰
    2021-02-09 02:21

    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.

提交回复
热议问题