首页 > 解决方案 > GCP cloudbuild.yaml 条件步骤错误

问题描述

这是我的云构建文件

substitutions:
        _CLOUDSDK_COMPUTE_ZONE: us-central1-a 
        _CLOUDSDK_CONTAINER_CLUSTER: $_CLOUDSDK_CONTAINER_CLUSTER
    steps:
    - name: gcr.io/$PROJECT_ID/sonar-scanner:latest
      entrypoint: 'bash'
      args:
      - '-c'
      - 'if [ $BRANCH_NAME != 'production' ]; then sonar-scanner -Dsonar.host.url=https://sonar.test.io -Dsonar.login=${_SONAR_LOGIN} -Dsonar.projectKey=service -Dsonar.sources=. ; fi'
    - id: 'build test-service image'
      name: 'gcr.io/cloud-builders/docker'
      args: ['build', '-t', 'gcr.io/$PROJECT_ID/$REPO_NAME/$BRANCH_NAME:$SHORT_SHA', '.']
    - id: 'push test-service image'
      name: 'gcr.io/cloud-builders/docker'
      args: ['push', 'gcr.io/$PROJECT_ID/$REPO_NAME/$BRANCH_NAME:$SHORT_SHA']
    - id: 'set test-service image in yamls'
      name: 'ubuntu'
      args: ['bash','-c','sed -i "s,TEST_SERVICE,gcr.io/$PROJECT_ID/$REPO_NAME/$BRANCH_NAME:$SHORT_SHA," k8s/*.yaml']
    - id: kubectl-apply
      name: 'gcr.io/cloud-builders/kubectl'
      args: ['apply', '-f', 'k8s/']
      env:
      - 'CLOUDSDK_COMPUTE_ZONE=${_CLOUDSDK_COMPUTE_ZONE}'
      - 'CLOUDSDK_CONTAINER_CLUSTER=${_CLOUDSDK_CONTAINER_CLUSTER}'
    images: ['gcr.io/$PROJECT_ID/$REPO_NAME/$BRANCH_NAME:$SHORT_SHA']

我收到错误

解组构建配置 cloudbuild.yaml 失败:yaml:第 17 行:未找到预期的密钥

更新 1

根据@cloudomation 建议,如果条件更新

- 'if [ $BRANCH_NAME != "production" ]; then sonar-scanner -Dsonar.host.url=https://sonar.test.io -Dsonar.login=${_SONAR_LOGIN} -Dsonar.projectKey=service -Dsonar.sources=. ; fi'

条件正常,但当它是真的得到这个错误

Step #1: Digest: sha256:ef0de1c8e48544b9693b9aab2222bf849028bb66881762bf77e055b0abbf7f2b Step #1: Status: Downloaded newer image for gcr.io/wotnot-235414/sonar-scanner:latest Step #1: gcr.io/project-235414/sonar-scanner:latest Step #1: /opt/sonar-scanner-3.2.0.1227-linux/bin/sonar-scanner: exec: line 59: /opt/sonar-scanner-3.2.0.1227-linux/jre/bin/java: not found Finished Step #1 ERROR ERROR: build step 1 "gcr.io/project-235414/sonar-scanner:latest" failed: exit status 127

但是当我的步骤像这样时,它工作得很好

- name: gcr.io/$PROJECT_ID/sonar-scanner:latest
  args:
    - '-Dsonar.host.url=https://sonar.test.io'
    - '-Dsonar.login=XXXXXXXXXXXXXX'
    - '-Dsonar.projectKey=service-name'
    - '-Dsonar.sources=.'

这也正在运行,这意味着构建器映像中没有问题,这只是传递参数的问题

docker run gcr.io/$PROJECT_ID/sonar-scanner:latest bash -Dsonar.host.url=https://sonar.test.io -Dsonar.login=${_SONAR_LOGIN} -Dsonar.projectKey=service -Dsonar.sources=.

如果条件正常,但在那之后,条件有一些问题

标签: google-cloud-platformgoogle-cloud-build

解决方案


您应该转义引号:

  - 'if [ $BRANCH_NAME != \'production\' ]; then sonar-scanner -Dsonar.host.url=https://sonar.test.io -Dsonar.login=${_SONAR_LOGIN} -Dsonar.projectKey=service -Dsonar.sources=. ; fi'

或使用双引号:

  - 'if [ $BRANCH_NAME != "production" ]; then sonar-scanner -Dsonar.host.url=https://sonar.test.io -Dsonar.login=${_SONAR_LOGIN} -Dsonar.projectKey=service -Dsonar.sources=. ; fi'

推荐阅读