Translating template from docker swarm to kubernetes

3/23/2021

I have a following docker command:

docker service inspect --format {{.Spec.TaskTemplate.ContainerSpec.Env}} my_service_name")?

Is there exists analogous template command for k8s?

-- IntrestedInSpark
docker
docker-swarm
kubectl
kubernetes

1 Answer

3/29/2021

In kubernetes, there are multiple object types that are analogous to a docker swarm service: deployments, replicasets, and statefulsets.

Each object in kubernetes can be accessed via kubectl. For example, if I have a deployment called my_deployment_name, I can do kubectl get deployment/my_deployment_name and get information about that deployment. I can change the output format as well, including a go template type format similar to what you are using on swarm.

The main difference between these kubernetes objects and swarm is that instead of specifying a swarm task template that in turn creates one container, it specifies a pod template, which can include multiple containers. This means that you'll need to handle the list of containers and look at the env in each one. Here's an example showing how to look at all containers environment values in a given deployment:

kubectl get deployment/my_deployment_name -o go-template='{{range .spec.template.spec.containers}}{{.env}}{{end}}'

Another way to deal with a kubernetes object is to get raw json or yaml and then use other tools to parse those. Here's a json + jq example that will return the value of env if it exists or false if it does not:

kubectl get deployment/my_deployment_name -o json | jq '.spec.template.spec.containers[] | .env // false'

and another example, but with yaml + yq:

kubectl get deployment/my_deployment_name -o yaml | yq eval '.spec.template.spec.containers[].env' -

You'll have a bit more parsing to do with these commands; Kubernetes doesn't return a simple list of variables in this api-- it's possible that some have a valueFrom that refer to another kubernetes object (such as a secret).

There are very similar commands for replicasets and statefulsets. The easiest way to see the layout of a kubernetes object is to run kubectl get -o yaml <resourcetype>/<resourcename> and you can build a template from there.

Full docs on kubectl get can be found here: https://kubernetes.io/docs/reference/generated/kubectl/kubectl-commands#get

-- programmerq
Source: StackOverflow