How to get specific container from init containers in kubernetes?

9/12/2021

I have the following code:

config.load_incluster_config()
v1 = client.CoreV1Api()
my_init_containers = v1.read_namespaced_pod(namespace=NAMESPACE, name=pod_name).spec.init_containers

This gives me all the containers in init_containers. My problem is that I want to get only specific container: git-sync-init-container.

I can do:

init = v1.read_namespaced_pod( namespace=NAMESPACE, name=pod_name).spec.init_containers[2]

But I don't want to use indexes. How can I get a container by name? I tried to iterate over my_init_containers searching for name=git-sync-init-container but this is a V1Container type and it doesn't let me iterate over it.

-- Slava
kubernetes
python

1 Answer

9/12/2021

You are close:

my_init_containers = v1.read_namespaced_pod(namespace=NAMESPACE, name=pod_name).spec.init_containers
for container in my_init_containers:
    if container.name == "the_one_im_looking_for":
        init = container
        break
-- anemyte
Source: StackOverflow