简体   繁体   English

如何通过 cli / rest api / 云功能运行 Google Cloud Build 触发器?

[英]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.我看到这个视频CI/CD 用于混合和多云客户 (Cloud Next '18)宣布有 API 触发器支持,我不确定这是否是我需要的。

I did same thing few days ago. 几天前我做了同样的事情。

You can submit your builds using gcloud and rest api 您可以使用gcloud和rest api提交构建

gcloud: gcloud:

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

Rest API: 休息API:

Send you cloudbuild.yaml as JSON with Auth Token to this url https://cloudbuild.googleapis.com/v1/projects/standf-188123/builds?alt=json 使用Auth Token将带有JSON的cloudbuild.yaml发送到此URL https://cloudbuild.googleapis.com/v1/projects/standf-188123/builds?alt=json

example cloudbuild.yaml: 示例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: 例子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"}]}

This now seems to be possible via API: 现在似乎可以通过API:

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

request.json: request.json:

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

curl request (with using a gcloud command): curl请求(使用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

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 具有标准API端点的HTTP触发器
  2. A pubsub trigger that you invoke by sending a message to a pubsub topic 通过向pubsub主题发送消息来调用的pubsub触发器

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. 第一种是更常见的方法,因为您有效地创建了一个Web API,任何客户端都可以使用他们选择的HTTP库调用它。

You can use google client api to create build jobs with python: 您可以使用google客户端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, [])

Here is the documentation so that you can implement more functionality: https://cloud.google.com/cloud-build/docs/api 以下是文档,您可以实现更多功能: https//cloud.google.com/cloud-build/docs/api

Hope this helps. 希望这可以帮助。

you can trigger a function via 你可以通过触发功能

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

inside your function you can do pretty much anything possibile within Googles Public API's 在你的功能中,你可以在Googles Public API中做任何可能的事情

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. 如果你只想从git直接触发Google Cloud Builder,那么可能建议使用Release版本标签 - 所以你的聊天机器人可能会在git中向你的发布分支添加一个发布标签,此时cloud-builder将启动构建。

more info here https://cloud.google.com/cloud-build/docs/running-builds/automate-builds 更多信息,请访问https://cloud.google.com/cloud-build/docs/running-builds/automate-builds

You should be able to manually trigger a build using curl and a json payload. 您应该能够使用curl和json有效负载手动触发构建。 For details see: https://cloud.google.com/cloud-build/docs/running-builds/start-build-manually#running_builds . 有关详细信息,请参阅: 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. 鉴于此,您可以编写Python Cloud函数以通过请求模块复制curl调用。

I was in search of the same thing (Fall 2022) and while I haven't tested yet I wanted to answer before I forget.我正在寻找同样的东西(2022 年秋季),虽然我还没有测试过,但我想在忘记之前回答。 It appears to be available now in gcloud beta builds triggers run TRIGGER它现在似乎可以在gcloud beta builds triggers run TRIGGER中使用

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 是否可以在 GCP 中通过云功能或云运行来触发云内存存储? - Is it possible to trigger cloud memorystore by cloud functions or cloud run in GCP? 如何通过 CLI 获取 Google Cloud SQL 实例的 IP - How to get IP of Google Cloud SQL instance via CLI Google Cloud Builder - 如何触发子目录中的构建配置? - Google Cloud Builder - how to trigger build configuration in a subdirectory? 如何完全自动化 Google Cloud Build 触发器的创建 - How to fully automate the Google Cloud Build trigger creation 通过触发器进行 GCP 云构建:Dockerfile 未找到 - GCP Cloud Build via trigger: Dockerfile not found 谷歌云构建、云运行、云 SQL Prisma 迁移 - Google Cloud Build, Cloud Run, Cloud SQL Prisma Migration 如何通过REST api获取谷歌云平台警报状态 - How to get google cloud platform alert status via REST apis 通过 Cloud Firestore 添加阵列 REST API - Add array via Cloud Firestore REST API 如何在启用身份验证的情况下将 reactJS 应用程序与 Google Cloud Functions 和 Cloud Run 集成? - How to integrate reactJS app with Google Cloud Functions and Cloud Run with authentication enabled? Google Cloud Build/Run 触发合并特定分支的拉取请求 - Google Cloud Build/Run trigger upon Pull Request on merge with specific branch
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM