pythonkubernetesazure-aks

How read a file from a pod in Azure Kubernetes Service (AKS) in a Pythonic way?


I have a requirement to read a file which is located inside a particular folder in a pod in AKS.

My manual flow would be to:

  1. exec into the pod with kubectl.
  2. cd to the directory where the file is located.
  3. cat the file to see it's contents.

I want to automate all this purely using python. I am able to do it with subprocess but that would work only on a machine which has azure and kubectl setup.

Thus, I am looking for a purely pythonic way of doing this. I have looked into the Kubernetes client for Python but I am not able to find a way to do everything which I listed above.


Solution

  • To read a file which is located inside a particular folder in a pod in AKS via Python script, follow the below steps

    Assuming you have a valid aks cluster up and running, deploy a pod with your desired file.

    For example -

    apiVersion: v1
    kind: Pod
    metadata:
      name: my-pod
      labels:
        app: my-app
    spec:
      containers:
      - name: my-container
        image: busybox
        command: ["/bin/sh", "-c", "echo 'Hello from AKS' > /data/file.txt && sleep 3600"]
        volumeMounts:
        - name: data-volume
          mountPath: "/data"
      volumes:
      - name: data-volume
        emptyDir: {}
    
    kubectl apply -f pod.yaml
    kubectl get pods
    

    enter image description here

    enter image description here

    This one says `Hello from AKS' and it should reflect the same when you read the file from the pod using python.

    Install / update the necessary dependencies

    pip install kubernetes

    Here's the script-

    from kubernetes import client, config, stream
    
    def read_file_from_pod(namespace: str, pod_name: str, container_name: str, file_path: str) -> str:
        try:
            config.load_incluster_config()
        except config.config_exception.ConfigException:
            config.load_kube_config()
    
        api_instance = client.CoreV1Api()
        command = ["cat", file_path]
    
        try:
            exec_response = stream.stream(
                api_instance.connect_get_namespaced_pod_exec,
                name=pod_name,
                namespace=namespace,
                command=command,
                container=container_name,
                stderr=True,
                stdin=False,
                stdout=True,
                tty=False,
            )
            return exec_response
        except Exception as e:
            return f"Error reading file from pod: {str(e)}"
    
    if __name__ == "__main__":
        namespace = "default"
        pod_name = "my-pod"
        container_name = "my-container"
        file_path = "/data/file.txt"
    
        file_contents = read_file_from_pod(namespace, pod_name, container_name, file_path)
        print("File Contents:", file_contents)
    
    

    Save and run the script. Now you can read a file from a pod in AKS in a Pythonic way.

    enter image description here