🐶
Kubernetes

Access Kubernetes API From Pod Container

By Jan on 02/03/2025

Learn different methods with code examples to securely access the Kubernetes API from your pod containers and interact with your cluster resources.

Access Kubernetes API From Pod Container

Table of Contents

Introduction

Accessing the Kubernetes API from within a pod is a common requirement for applications running in a Kubernetes cluster. This allows pods to interact with cluster resources, such as creating deployments, listing services, or fetching secrets. Here's how you can access the Kubernetes API from within your pod containers:

Step-by-Step Guide

  1. Every pod automatically gets a service account. This service account provides the necessary credentials to access the Kubernetes API server.

    apiVersion: v1
    kind: Pod
    metadata:
      name: my-pod
    spec:
      containers:
      - name: my-container
        image: my-image
  2. The credentials are stored within the pod's filesystem. You can find them at /var/run/secrets/kubernetes.io/serviceaccount.

    ls /var/run/secrets/kubernetes.io/serviceaccount
  3. Use a Kubernetes client library to interact with the API server. These libraries handle authentication and communication details.

    from kubernetes import client, config
    
    config.load_incluster_config()
    v1 = client.CoreV1Api()
    
    pods = v1.list_pod_for_all_namespaces(watch=False)
    for pod in pods.items:
        print(f"{pod.metadata.namespace} {pod.metadata.name}")
  4. Specify the API server address and port. This information is available in the kubernetes.default.svc service.

    KUBERNETES_SERVICE_HOST=kubernetes.default.svc
    KUBERNETES_SERVICE_PORT=443
    
  5. Access the API server using HTTPS. The certificate authority bundle is located within the pod's filesystem.

    CA_CERT=/var/run/secrets/kubernetes.io/serviceaccount/ca.crt
    

By following these steps, you can easily access the Kubernetes API from within your pod containers and interact with your cluster resources programmatically.

Code Example

This code provides a step-by-step guide for listing all pods in a Kubernetes cluster from within a pod using Python. It includes creating a Python script that utilizes the Kubernetes Python client library to authenticate and interact with the API server, building a Docker image containing the script and dependencies, pushing the image to a registry, defining a Kubernetes deployment to run the pod, and finally, applying the deployment to the cluster. The script leverages the pod's service account for authentication and can be modified for other Kubernetes API operations.

This example demonstrates how to list all pods in the cluster from within a pod using the Python Kubernetes client library.

1. Create a Python script named list_pods.py:

from kubernetes import client, config

# Load in-cluster configuration
config.load_incluster_config()

# Create a CoreV1Api instance
v1 = client.CoreV1Api()

# List all pods in all namespaces
pods = v1.list_pod_for_all_namespaces(watch=False)

# Print the namespace and name of each pod
for pod in pods.items:
    print(f"{pod.metadata.namespace} {pod.metadata.name}")

2. Create a Dockerfile to build your image:

FROM python:3.9-slim-buster

WORKDIR /app

COPY requirements.txt ./
RUN pip install --no-cache-dir --upgrade -r requirements.txt

COPY list_pods.py ./

CMD ["python", "./list_pods.py"]

3. Create a requirements.txt file:

kubernetes

4. Build and push the Docker image to your registry:

docker build -t your-registry/list-pods:latest .
docker push your-registry/list-pods:latest

5. Create a Kubernetes deployment to run your pod:

apiVersion: apps/v1
kind: Deployment
metadata:
  name: list-pods-deployment
spec:
  replicas: 1
  selector:
    matchLabels:
      app: list-pods
  template:
    metadata:
      labels:
        app: list-pods
    spec:
      containers:
      - name: list-pods
        image: your-registry/list-pods:latest

6. Apply the deployment to your cluster:

kubectl apply -f deployment.yaml

This will create a pod that runs your Python script. The script will use the service account attached to the pod to authenticate with the Kubernetes API server and list all pods in the cluster.

Note: This is a basic example. You can modify the script to perform other Kubernetes API operations, such as creating, updating, or deleting resources.

Additional Notes

These notes expand on the provided information, offering deeper insights and practical considerations:

Service Accounts:

  • Default Service Account: While every pod automatically gets a service account, it's a best practice to explicitly define and assign service accounts with least privilege principle in mind. This enhances security by limiting the pod's access to only the resources it needs.
  • Role-Based Access Control (RBAC): Kubernetes uses RBAC to control access to the API server. You can create Roles and RoleBindings (or ClusterRoles and ClusterRoleBindings for cluster-wide access) to define which service accounts have permission to perform specific actions on specific resources.

Credentials and Authentication:

  • Security Best Practices: Avoid hardcoding API server addresses or credentials within your application code or Docker images. Instead, rely on the service account and in-cluster configuration mechanisms for secure and dynamic access.
  • Token Refreshing: The service account tokens have an expiration time. Kubernetes automatically handles token refreshing, so you typically don't need to manage this yourself.

Kubernetes Client Libraries:

  • Language Support: Client libraries are available for various programming languages, making it convenient to interact with the Kubernetes API from your preferred language.
  • Abstraction and Convenience: Client libraries abstract away the complexities of API communication, authentication, and object serialization, simplifying your application code.

API Server Access:

  • Service Discovery: The kubernetes.default.svc service provides a stable endpoint to access the API server from within the cluster, even if the API server's IP address changes.
  • HTTPS and Security: Communication with the API server is always encrypted using HTTPS. The certificate authority bundle provided within the pod ensures secure communication.

Additional Considerations:

  • Error Handling: Implement robust error handling in your code to gracefully handle situations where the API server is unavailable or returns errors.
  • Resource Limits: Be mindful of resource consumption when interacting with the Kubernetes API. Excessive requests can impact the performance of the API server and your cluster.
  • Observability: Monitor your application's interactions with the Kubernetes API to identify potential issues and ensure optimal performance.

By understanding these concepts and following best practices, you can securely and effectively access the Kubernetes API from within your pods, enabling your applications to interact with the cluster and manage resources programmatically.

Summary

This article outlines how to access the Kubernetes API from within a pod. Here's a breakdown:

Key Points:

  • Automatic Service Account: Every pod automatically receives a service account with credentials for accessing the API server.
  • Credential Location: These credentials are stored within the pod's filesystem at /var/run/secrets/kubernetes.io/serviceaccount.
  • Client Libraries: Utilize Kubernetes client libraries (e.g., Python's kubernetes library) to simplify API interaction, handling authentication and communication.
  • API Server Details: The API server address (kubernetes.default.svc) and port (443) are accessible through environment variables.
  • Secure Communication: Connect to the API server using HTTPS, with the certificate authority bundle located at /var/run/secrets/kubernetes.io/serviceaccount/ca.crt.

In Essence:

By leveraging the provided service account, environment variables, and client libraries, you can securely interact with the Kubernetes API from within your pod containers, enabling programmatic management of cluster resources.

Conclusion

In conclusion, accessing the Kubernetes API from within a pod is a crucial aspect of developing and deploying applications within a Kubernetes environment. By leveraging the inherent service account mechanism, utilizing appropriate client libraries, and adhering to security best practices, developers can seamlessly integrate their applications with the Kubernetes API. This enables applications to perform a wide range of actions, including resource management, service discovery, and event monitoring, ultimately empowering them to operate effectively and dynamically within the Kubernetes ecosystem.

References

  • Accessing the Kubernetes API from a Pod | Kubernetes Accessing the Kubernetes API from a Pod | Kubernetes | This guide demonstrates how to access the Kubernetes API from within a pod. Before you begin You need to have a Kubernetes cluster, and the kubectl command-line tool must be configured to communicate with your cluster. It is recommended to run this tutorial on a cluster with at least two nodes that are not acting as control plane hosts. If you do not already have a cluster, you can create one by using minikube or you can use one of these Kubernetes playgrounds:
  • Access Clusters Using the Kubernetes API | Kubernetes Access Clusters Using the Kubernetes API | Kubernetes | Production-Grade Container Orchestration
  • Access Clusters Using the Kubernetes API | Kubernetes Access Clusters Using the Kubernetes API | Kubernetes | This page shows how to access clusters using the Kubernetes API. Before you begin You need to have a Kubernetes cluster, and the kubectl command-line tool must be configured to communicate with your cluster. It is recommended to run this tutorial on a cluster with at least two nodes that are not acting as control plane hosts. If you do not already have a cluster, you can create one by using minikube or you can use one of these Kubernetes playgrounds:
  • Accessing the Kubernetes API from a Pod | by Prathap | Medium Accessing the Kubernetes API from a Pod | by Prathap | Medium | Lets first create a pod using ubuntu image and below is the YAML file (ubuntu-pod.yaml),
  • Is there way to access region/zone information of pod inside ... Is there way to access region/zone information of pod inside ... | Hi I was trying to get pod zone/region information using environment variable inside container. I was able to get pod name using below config. Please help me to get zone/region information. --- kind: Deployment apiVersion: extensions/v1beta1 metadata: name: rc-sample namespace: default labels: app: rc-sample annotations: deployment.kubernetes.io/revision: '1' spec: replicas: 1 selector: matchLabels: app: rc-sample template: metadata: name: rc-sample ...
  • How to access Kubernetes API's from a Pod? here's a solution | by ... How to access Kubernetes API's from a Pod? here's a solution | by ... | There are few ways, here I’m detailing service account approach.
  • Cannot access pod services from another pod - Discuss Kubernetes Cannot access pod services from another pod - Discuss Kubernetes | I can´t access the containers services from another container using services ports (I tried with ClusterIP, NodePort). The service is ok when I access it from a node in my network using the NodePort service. [ root@curl-5858f4ff79-s86n7:/ ]$ nslookup example-svc Server: 10.96.0.10 Address 1: 10.96.0.10 kube-dns.kube-system.svc.cluster.local Name: example-svc Address 1: 10.103.131.13 example-svc.svc.cluster.local [ root@curl-5858f4ff79-s86n7:/ ]$ telnet example-svc 5672 Connection...
  • What permissions does a pod have when accessing the Kubernetes ... What permissions does a pod have when accessing the Kubernetes ... | Aug 6, 2020 ... ... Accessing the API from within a Pod": The easiest way to use the Kubernetes API from a Pod is to use one of the official client libraries.
  • Kubernetes API service not responding - General Discussions ... Kubernetes API service not responding - General Discussions ... | Hello, I’m a newbie was trying to setup a basic Kubernetes environment with one Master node and one Worker node. I’m facing this problem where constantly my master node API service abruptly stops responding, and if I restart ‘kubelet’ service it works for couple of minutes and again it stops and gives following error. Please help me fix this problem because I stuck with this issue since last three days and i’m not able to figure out the root cause for this problem. Thank you. ubadmin@kuber...

Were You Able to Follow the Instructions?

😍Love it!
😊Yes
😐Meh-gical
😞No
🤮Clickbait