google 云构建语法

google cloud build syntax

我正在处理我的第一个 cloudbuild.yaml 文件,运行 遇到此错误:

Your build failed to run: failed unmarshalling build config cloudbuild.yaml: yaml: line 8: did not find expected key

下面是我的文件内容(注释省略),后面有几个问题:

steps:
- name: 'node:12-alpine'
    entrypoint: 'bash'
    args:
        - 'build.sh'
- name: 'docker'
    args:
    - 'build'
    - '-t'
    - 'gcr.io/$PROJECT_ID/my-project:$(git describe --tags `git rev-list --tags --max-count=1`)'
images: ['gcr.io/$PROJECT_ID/my-project']

问题:

此错误很可能是由于 cloudbuild.yaml 文件的缩进错误造成的。 你可以看看official documentation,它显示了这个文件的结构:

steps:
- name: string
  args: [string, string, ...]
  entrypoint: string
- name: string
  ...
- name: string
  ...
images:
- [string, string, ...]

当你运行一个容器进入Cloud Build时,定义到容器中的入口点会被自动调用,并且args传入这个入口点的参数。

你必须知道的

  • 您可以覆盖入口点,就像您在 node:12 图像中所做的那样
  • 如果容器不包含入口点,则构建失败(您的错误,您使用了通用 docker 图像)。你可以
    • 要么定义正确的入口点(此处entrypoint: "docker"
    • 或者用一个Cloud Builder,对于docker,这个- name: 'gcr.io/cloud-builders/docker'
  • 步骤的参数被转发 as-is,没有任何解释(除了 $MyVariable 之类的变量替换)。您的命令解释 $(my command) 未被评估。除了你这样做
- name: 'gcr.io/cloud-builders/docker' #you can also use the raw docker image here
  entrypoint: 'bash'
  args:
    - '-c'
    - |
      first bash command line
      second bash command line
      docker build -t gcr.io/$PROJECT_ID/my-project:$(git describe --tags `git rev-list --tags --max-count=1`)

但是您可以让标签更智能。如果你看看 default environment variable of Cloud Build,你可以使用 $TAG_NAME.

docker build -t gcr.io/$PROJECT_ID/my-project:$TAG_NAME

请注意,只有当您从您的存储库中触发它时,它才是正确的。如果您 运行 手动构建,则它不起作用。所以,有一个解决方法。看看这个

- name: 'gcr.io/cloud-builders/docker' 
  entrypoint: 'bash'
  args:
    - '-c'
    - |
      TAG=${TAG_NAME}
      if [ -z $${TAG} ]; then TAG=$(git describe --tags `git rev-list --tags --max-count=1`); fi      
      docker build -t gcr.io/$PROJECT_ID/my-project:$${TAG}

但是,我不建议您覆盖图像。你会丢失历史,如果你用错误的版本覆盖了一个好的图像,你就失去了它!

如果你有什么地方没听懂,比如为什么双 $$ 等等,不要犹豫,评论