Google Cloud build conditional step

10/4/2019

This is my cloud build file

substitutions:
    _CLOUDSDK_COMPUTE_ZONE: us-central1-a 
    _CLOUDSDK_CONTAINER_CLUSTER: $_CLOUDSDK_CONTAINER_CLUSTER
steps:
- name: gcr.io/$PROJECT_ID/sonar-scanner:latest
  args:
    - '-Dsonar.host.url=https://sonar.test.io'
    - '-Dsonar.login=XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'
    - '-Dsonar.projectKey=test-service'
    - '-Dsonar.sources=.'
- 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']

i would like to implement condition step. Where my sonar step is there.

If branch is production i have to skip sonar step and if other branches is there have to run step.

I want to manage same Cloudbuild.yaml across all branches.

as I merge branches development > staging > production.

So is it possible with cloud build to implement conditional step ?

-- Harsh Manvar
google-cloud-build
google-cloud-platform
google-kubernetes-engine

1 Answer

10/4/2019

You have 2 solutions

  1. Make 2 triggers, each one with their own configuration. 1 on Prod, 1 on UAT/DEV.
  2. You can script your execution. It's dirty but you keep only 1 CI/CD config file
steps:
- name: gcr.io/$PROJECT_ID/sonar-scanner:latest
  entrypoint: 'bash'
  args:
    - '-c'
    - 'if [ $BRANCH_NAME != 'prod' ]; then sonar-scanner -Dsonar.host.url=https://sonar.test.io -Dsonar.login=XXXX -Dsonar.projectKey=test-service -Dsonar.sources=. ; fi'
-- guillaume blaquiere
Source: StackOverflow