In order to demonstrate the API query we will build a custom docker image.
It is optional to use the pre-build image and skip this step.
Step 01 - The script which will be used for query K8S API¶
In order to be able to access K8S API from within a pod, we will be using the following script:
# `api_query.sh`#!/bin/sh################################### Access the internal K8S API #################################### Point to the internal API server hostnameAPI_SERVER_URL=https://kubernetes.default.svc
# Path to ServiceAccount token# The service account is mapped by the K8S Api server in the podsSERVICE_ACCOUNT_FOLDER=/var/run/secrets/kubernetes.io/serviceaccount
# Read this Pod's namespace if required# NAMESPACE=$(cat ${SERVICE_ACCOUNT_FOLDER}/namespace)# Read the ServiceAccount bearer tokenTOKEN=$(cat${SERVICE_ACCOUNT_FOLDER}/token)# Reference the internal certificate authority (CA)CACERT=${SERVICE_ACCOUNT_FOLDER}/ca.crt
# Explore the API with TOKEN and the Certificatecurl--cacert${CACERT}--header"Authorization: Bearer ${TOKEN}"-XGET${API_SERVER_URL}/api
For the pod image we will use the following Dockerfile:
# `Dockerfile`FROMalpine# Update and install dependenciesRUNapkadd--updatenodejsnpmcurl
# Copy the endpoint scriptCOPYapi_query.sh.
# Set the execution bitRUNchmod+xapi_query.sh.
Run the following script to verify that the connection to the API is working:
# Get the deployment pod namePOD_NAME=$(kubectlgetpod-A-lapp=monitor-app-ojsonpath="{.items[0].metadata.name}")# Print out the logs to verify that the pods is connected to the APIkubectlexec-it-ncodewizard$POD_NAMEsh./api_query.sh