Search code examples
dockergoogle-cloud-platformgoogle-cloud-buildkanikocloudbuild.yaml

How to use Kaniko in cloudbuild.yaml?


I just learned that one can speed up the build process in Google Cloud build by using Kaniko cache. I looked at the docs and it provided a small example. However, I'm not sure how to apply it in my use case. I am basically pushing a Nuxt app into my Github repo and cloud builds it every time I make a push. The docs example says we need to replace cloud-builders/docker with kaniko-project/executor:latest. Below is a snippet of my cloudbuild.yaml

steps:
# Create .npmrc file from Fontawesome secret
- name: gcr.io/cloud-builders/gcloud
  entrypoint: 'bash'
  args: [ '-c', 'gcloud secrets versions access latest --secret=fontawesome > .npmrc' ]
# Build the container image
- name: 'gcr.io/cloud-builders/docker'
  args: ['build', '-t', 'gcr.io/PROJECTNAME/IMAGENAME:$COMMIT_SHA', '.']
# Push the image to Container Registry
- name: 'gcr.io/cloud-builders/docker'
  args: ['push', 'gcr.io/PROJECTNAME/IMAGENAME:$COMMIT_SHA']

Kaniko docs says I need the following:

steps:
- name: 'gcr.io/kaniko-project/executor:latest'
  args:
  - --destination=gcr.io/$PROJECT_ID/image
  - --cache=true
  - --cache-ttl=XXh

This is what I tried (but not sure if that's how it should be):

steps:
    # Create .npmrc file from Fontawesome secret
    - name: gcr.io/cloud-builders/gcloud
      entrypoint: 'bash'
      args: [ '-c', 'gcloud secrets versions access latest --secret=fontawesome > .npmrc' ]
    # Build the container image
    - name: 'gcr.io/kaniko-project/executor:latest'
      args: ['--destination=gcr.io/$PROJECT_ID/image', '--cache=true', '--cache-ttl=6h'
,'build', '-t', 'gcr.io/PROJECTNAME/IMAGENAME:$COMMIT_SHA', '.']
    # Push the image to Container Registry
    - name: 'gcr.io/kaniko-project/executor:latest'
      args: ['--destination=gcr.io/$PROJECT_ID/image', '--cache=true', '--cache-ttl=6h'
, 'push', 'gcr.io/PROJECTNAME/IMAGENAME:$COMMIT_SHA']

Solution

  • Kaniko doesn't have push and build command. It will do that implicitly (build and push) when you specify it as a build step in cloudbuild.yaml.

    an example would be:

    steps:
      # Build the container image and push it with Kaniko
      - name: 'gcr.io/kaniko-project/executor:latest'
        args:
          [
            "--dockerfile=<DOCKER-FILE-DIST>",
            "--context=dir://<BUILD_CONTEXT>",
            "--cache=true",
            "--cache-ttl=6h",
            "--destination=gcr.io/$PROJECT_ID/hello:$COMMIT_SHA"
          ]
      # Deploy image to Cloud Run
      - name: "gcr.io/cloud-builders/gcloud"
        args:
          - "run"
          - "deploy"
          - "hello"
          - "--image"
          - "gcr.io/$PROJECT_ID/hello:$COMMIT_SHA"
          - "--region"
          - "us-central1"
          - "--platform"
          - "managed"