How to execute python script on Azure AKS - Job Deployment

289 views Asked by At

I am trying to execute a simple python script via Azure Cloud Shell (Powershell) that generates a simple log via a Kubernates Job, using the following yaml file:

    apiVersion: batch/v1
kind: Job
metadata:
  name: your-job-name
spec:
  template:
    spec:
      containers:
      - name: your-container-name
        image: python:3
        command: ["python", "your-script.py"]
      restartPolicy: Never

This is the python script:

    import sys
import datetime as dt

def print_to_stdout(*a):

    # Here a is the array holding the objects
    # passed as the argument of the function
    print(*a, file=sys.stdout)
    
# Save the current time to a variable ('t')
t = dt.datetime.now()

while True:
    delta = dt.datetime.now()-t
    if delta.seconds >= 30:
        print_to_stdout("Hello World, half minute has passed")
        # Update 't' variable to new time
        t = dt.datetime.now()

But I am getting stuck on this error: python: can't open file '//your-script.py': [Errno 2] No such file or directory.

Any hint on how to solve this. It seems like python cannot find the file with the source code.

1

There are 1 answers

1
HowAreYou On

It appears that the script file is not available within the container. In order to get it work, you need to mount the script file as a volume to the container or create a custom container.

I have followed the below steps to execute python script on kubernetes job. I created a custom python docker image with script included. Below is the Dockerfile to create custom python image. Dockerfile:

FROM python:3
WORKDIR /app
COPY pyscript.py .
CMD ["python", "pyscript.py"]

Next I pushed to the ACR registry. https://i.imgur.com/QxiYBfN.png

Now I connected to the kubernetes and created kubernetes job as below.

apiVersion: batch/v1
kind: Job
metadata:
  name: pyjob02
spec:
  template:
    metadata:
      name: pyjob02
    spec:
      containers:
      - name: pyjobcont
        image: acrvjyawesome.azurecr.io/python:3
        command: ["python", "pyscript.py"]
      restartPolicy: Never
  backoffLimit: 4

I created a kubernetes job and below is the output. https://i.imgur.com/d08DDqQ.png