Merge "Add action for getting container names list"

This commit is contained in:
Zuul 2025-03-24 14:17:36 +00:00 committed by Gerrit Code Review
commit b2fb42f32c
2 changed files with 37 additions and 1 deletions

View File

@ -46,7 +46,7 @@ options:
- The action to perform
required: True
type: str
author: Jeffrey Zhang, Michal Nasiadka
author: Jeffrey Zhang, Michal Nasiadka, Ivan Halomi
'''
EXAMPLES = '''
@ -89,6 +89,11 @@ EXAMPLES = '''
kolla_container_facts:
container_engine: docker
action: get_volumes
- name: Get container names
kolla_container_facts:
container_engine: docker
action: get_containers_names
'''
@ -122,6 +127,12 @@ class ContainerFactsWorker():
envs[key] = value
return envs
def get_containers_names(self):
"""Handles when module is called with action get_containers_names"""
containers = self.client.containers.list()
names = [cont.name for cont in containers]
self.result['container_names'] = names
def get_containers(self):
"""Handle when module is called with action get_containers"""
names = self.params.get('name')
@ -216,6 +227,7 @@ def main():
choices=['get_containers',
'get_containers_env',
'get_containers_state',
'get_containers_names',
'get_volumes']),
)

View File

@ -310,3 +310,27 @@ class TestContainerFacts(base.BaseTestCase):
self.assertIn('volumes', self.dfw.result)
self.assertEqual(len(self.dfw.result['volumes']), 0)
self.assertNotIn('nonexistent_volume', self.dfw.result['volumes'])
def test_get_containers_names(self):
"""Test fetching container names when containers exist"""
self.dfw = get_DockerFactsWorker({'action': 'get_containers_names'})
full_cont_list = get_containers(self.fake_data['containers'])
self.dfw.client.containers.list.return_value = full_cont_list
expected_names = ["my_container"]
self.dfw.get_containers_names()
self.assertFalse(self.dfw.result['changed'])
self.assertIn('container_names', self.dfw.result)
self.assertEqual(self.dfw.result['container_names'], expected_names)
def test_get_containers_names_no_containers(self):
"""Test fetching container names when no containers exist"""
self.dfw = get_DockerFactsWorker({'action': 'get_containers_names'})
self.dfw.client.containers.list.return_value = []
self.dfw.get_containers_names()
self.assertFalse(self.dfw.result['changed'])
self.assertIn('container_names', self.dfw.result)
self.assertEqual(self.dfw.result['container_names'], [])