Home > database >  Chain multiple arguments (args) in Kubernetes
Chain multiple arguments (args) in Kubernetes

Time:12-10

I need to execute multiple line of code in a container, which getting passed as args, like in the following example: deployment.yaml excerpt

initContainers:
 - name: wait-for-migrations
   args:
    - python
    - -c
    - |
        print("python")
        ...more lines
    - bash
    - -c
    - |
        echo bash
        ...more lines


Right now, no matter what I have tried, I cannot get both python/bash to be executed.. only the first one always is. Chaining both with in-between:

- ;

Did not work either.

Any ideas how to implement it?

CodePudding user response:

I think it would be better to create a dedicated script for this. Doing it the way I am showing below is somewhat dirty.

It's a limitation of containers in general. You cannot run multiple commands. This has nothing to do with Kubernetes in that sense. The usual workaround for complex commands is to wrap everything in a single bash -c, i.e. bash -c "first command; second command". Often times we also see them join with && which would not execute any further commands if the current command failed, i.e. bash -c "first command && second command".

You don't have to separate those in command and args but I think it's a bit cleaner.

apiVersion: v1
kind: Pod
metadata:
  name: script
spec:
  containers:
    - name: script
      image: python
      command:
        - bash
        - -c
      args:
        - |
          echo "hello world";
          python -c '
          print("foo")
          print("bar")
          print("baz")
          ';
          sleep 180;

That said, since you want to wait for a migration, it may be cleaner to move the migration to a Kubernetes job and check the Kubernetes API in the init container if the job is finished. For example with kubectl. The migration job could run the same image as the main application but performing its migration command, if it has one.

apiVersion: batch/v1
kind: Job
metadata:
  name: migration
spec:
  ttlSecondsAfterFinished: 100
  template:
    spec:
      containers:
        - name: migration
          image: busybox
          command: ["/bin/sh", "-c", "sleep 20"]
      restartPolicy: Never
---
apiVersion: v1
kind: Pod
metadata:
  name: app
spec:
  containers:
    - name: app
      image: busybox
      command: ["/bin/sh", "-c", "sleep 100"]
  initContainers:
    - name: wait-for-migration
      image: bitnami/kubectl
      args:
        - wait
        - job/migration
        - --for
        - condition=complete
        - --timeout
        - 60s
  • Related