如何通过cli / rest api / cloud函数运行Google Cloud Build触发器?

时间:2018-08-19 06:38:19

标签: google-cloud-platform google-cloud-functions google-cloud-build

有这样的选择吗?我的用例将运行生产构建的触发器(部署到生产)。理想情况下,该触发器无需监听任何更改,因为它是通过chatbot手动调用的。

我看到这段视频CI/CD for Hybrid and Multi-Cloud Customers (Cloud Next '18)宣布有API触发器支持,我不确定这是否是我需要的。

6 个答案:

答案 0 :(得分:3)

几天前我做了同样的事情。

您可以使用gcloud和rest api提交构建版本

gcloud:

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

其他API:

使用身份验证令牌将您的cloudbuild.yaml发送给JSON https://cloudbuild.googleapis.com/v1/projects/standf-188123/builds?alt=json

示例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"]

示例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"}]}

答案 1 :(得分:1)

如果只想创建可以直接调用的函数,则有两种选择:

  1. 具有标准API端点的HTTP trigger
  2. 通过向pubsub主题发送消息而调用的pubsub trigger

第一种是更常见的方法,因为您正在有效地创建一个Web API,任何客户端都可以使用自己选择的HTTP库来调用它。

答案 2 :(得分:1)

您可以使用google client api通过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, [])

以下是文档,以便您可以实现更多功能:https://cloud.google.com/cloud-build/docs/api

希望这会有所帮助。

答案 3 :(得分:0)

您可以通过

触发功能

gcloud函数调用NAME --data'THING'

在您的函数中,您几乎可以在Googles Public API的范围内做任何事情

如果您只想直接从git触发Google Cloud Builder,则建议使用Release版本标签-因此,您的聊天机器人可能会向git中的release分支添加一个release标签,此时cloud-builder将开始构建。

更多信息,请点击https://cloud.google.com/cloud-build/docs/running-builds/automate-builds

答案 4 :(得分:0)

您应该能够使用curl和json负载手动触发构建。  有关详细信息,请参见:https://cloud.google.com/cloud-build/docs/running-builds/start-build-manually#running_builds

鉴于此,您可以编写Python Cloud函数来通过请求模块复制curl调用。

答案 5 :(得分:0)

现在似乎可以通过API来实现:

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

request.json:

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

卷曲请求(使用gcloud命令):

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