Search code examples
bashgoogle-cloud-platformyamlgoogle-cloud-buildcloudbuild.yaml

add small bash script to cloudbuild.yaml


I have a cloudbuild.yaml file for google cloud (GCP). I would like to grab the version from package.json using a simple bash script $(node -p -e "require('./package.json').version") (or any other way). How can I add this to my cloudbuild.yaml file?

I tried putting the script in substitution but it didn't work.

# gcloud submit   --substitutions=_VERSION="1.1.0"

steps:
  # build the container image
  - name: "gcr.io/cloud-builders/docker"
    args: ["build", "-t", "gcr.io/${_PROJECT_ID}/${_IMAGE}:${_VERSION}", "."]
  # push the container image to Container Registry
  - name: "gcr.io/cloud-builders/docker"
    args: ["push", "gcr.io/${_PROJECT_ID}/${_IMAGE}:${_VERSION}"]
  # build the container image
  - name: 'gcr.io/google.com/cloudsdktool/cloud-sdk'
    entrypoint: gcloud
    args:
      [
        "run",
        "deploy",
        "${_SERVICE_NAME}",
        "--project",
        "${_PROJECT_ID}",
        "--image",
        "gcr.io/${_PROJECT_ID}/${_IMAGE}:${_VERSION}",
        "--platform",
        "managed",
        "--allow-unauthenticated",
        "--region",
        "${_REGION}",
        "--set-env-vars",
        "${_ENV_VARS}",
        "--ingress",
        "internal-and-cloud-load-balancing",
        "--quiet",
      ]
images:
  - gcr.io/${_PROJECT_ID}/${_IMAGE}

substitutions:
  _REGION: us-east1
  _PROJECT_ID: my-dev
  _SERVICE_NAME: my-client
  _IMAGE: my-client
  _VERSION: $(node -p -e "require('./package.json').version")
  _ENV_VARS: "APP_ENV=dev"

Solution

  • Based on Guillaume's answer, you can use a bash script with two $$ instead of 1 $, like so $$(node -p -e "require('./package.json').version"). However, if the command you're attempting to use isn't available (node will not be available), it's best to pull it from a file that you can make in the step above like in Guillaume's answer:

    - name: "gcr.io/cloud-builders/docker"
        entrypoint: bash
        args: 
          - -c
          - docker build -t gcr.io/${_PROJECT_ID}/${_IMAGE}:$$(cat ./package_version) .
    

    UPDATE: This is our entire script

      - name: 'node'
        entrypoint: bash
        args:
          - -c
          - |
            echo "$(node -p -e "require('./package.json').version")-$BRANCH_NAME-$(git rev-parse --short HEAD)" | sed 's/\//-/g' > _VERSION
            echo "Building version $(cat _VERSION)"
    

    which prints <package-name>-<version>-<git_hash>