get pods belonging to a kubernetes replication controller

12/13/2015

I'm wondering whether there is a way using the kubernetes API to get the the details of the pods that belong to a given replication controller. I've looked at the reference and the only way as I see it, is getting the pods list and go through each one checking whether it is belongs to a certain RC by analysing the 'annotations' section. It's again a hard job since the json specifies the whole 'kubernetes.io/created-by' part as a single string.

-- Sudheera
api
kubernetes

2 Answers

12/14/2015

Every Replication Controller has a selector which defines the set of pods managed by it:

selector:
    label_name_1: some_value
    label_name_2: another_value

You can use the selector to get all the pods with a corresponding set of labels:

https://k8s.example.com/api/v1/pods?labelSelector=label_name_1%3Dsome_value,label_name_2%3Danother_value

-- msufa
Source: StackOverflow

2/5/2019

To get the details of pods belonging to a particular replication controller we need to include selector field in the yaml file that defines the replication controller and matching label fields in the template of the pod to be created. An example of a replication controller yaml file is given below:

apiVersion: v1
kind: ReplicationController
metadata:
  name: nginx
spec:
  replicas: 3
  selector:
    app: nginx
  template:
    metadata:
      name: nginx
      labels:
        app: nginx
    spec:
      containers:
      - name: nginx
        image: nginx
        ports:
        - containerPort: 80 

To list out the pod names use the command:

pods=$(kubectl get pods --selector=app=nginx --output=jsonpath={.items..metadata.name})
echo $pods

In the above command the --output=jsonpath option specifies the expression that just gets the name of each pod.

-- Manya Tripathi
Source: StackOverflow