How to use kaniko with --build-arg in Kubernetes pod

525 Views Asked by At

I'm a bit new with Kaniko, and looking at Kaniko documentation is not clear to me how to use --build-arg flag. Actually I'm running my build on Azure Devops pipeline. I have a script that create my Kaniko job on kubernetes cluster. The problem is that I'm trying to pass some variables in Kaniko execution to fill my dockerfile. This is how I'm trying to use:

apiVersion: batch/v1
kind: Job
metadata:
  name: kaniko-job-build
spec:
  template:
    spec:
      containers:
      - name: kaniko-executor
        image: myacrpath/kaniko-executor:v1.9.2
        args: ["--dockerfile=Dockerfilepath",
               "--context=context-to-be-updated",
               "--destination=image-to-be-updated",
               "--build-arg=BUILD_TYPE_ARG=$(BUILD_TYPE)",

The $(BUILD_TYPE) variable is comming from my pipeline, but is not filling properly on the dockerfile during Kaniko execution.

This is the correct usage of --build-arg flag? Do I need to pass this variables as env variables to my job manifest? I'm a bit lost on this and trying to figure out how to solve this issue. Thanks in advance!

1

There are 1 best solutions below

0
Alvin Zhao - MSFT On

Per the requirement to replace the variable in the k8s manifest .yml file with the variable value, you may consider using the Replace Tokens extension task in marketplace. Taking my pipeline below for example, the replacetokens@5 task will replace #{BUILD_TYPE}# in deployment.yml with its value XXXXX.

/manifests/deployment.yml


piVersion: batch/v1
kind: Job
metadata:
  name: kaniko-job-build
spec:
  template:
    spec:
      containers:
      - name: kaniko-executor
        image: myacrpath/kaniko-executor:v1.9.2
        args: ["--dockerfile=Dockerfilepath",
               "--context=context-to-be-updated",
               "--destination=image-to-be-updated",
               "--build-arg=BUILD_TYPE_ARG=#{BUILD_TYPE}#"]

azure-pipelines.yml

variables:
  BUILD_TYPE: XXXXX

steps:
- task: replacetokens@5
  inputs:
    targetFiles: '**/deployment.yml'
    encoding: 'auto'
    tokenPattern: 'default'
    writeBOM: true
    actionOnMissing: 'warn'
    keepToken: false
    actionOnNoFiles: 'continue'
    enableTransforms: false
    enableRecursion: false
    useLegacyPattern: false
    enableTelemetry: true

- script: cat manifests/deployment.yml

enter image description here