Skip to content

Commit 54f08e0

Browse files
sanjayprabSanjay Prabhakar
andauthored
[patch] add some ocp functions (#149)
Co-authored-by: Sanjay Prabhakar <sanjay.prabhakar@uk.ibm.com>
1 parent 9913f14 commit 54f08e0

1 file changed

Lines changed: 57 additions & 0 deletions

File tree

src/mas/devops/ocp.py

Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -243,6 +243,63 @@ def crdExists(dynClient: DynamicClient, crdName: str) -> bool:
243243
return False
244244

245245

246+
def getCR(dynClient: DynamicClient, cr_api_version: str, cr_kind: str, cr_name: str, namespace: str = None) -> dict:
247+
"""
248+
Get a Custom Resource
249+
"""
250+
251+
try:
252+
crAPI = dynClient.resources.get(api_version=cr_api_version, kind=cr_kind)
253+
if namespace:
254+
cr = crAPI.get(name=cr_name, namespace=namespace)
255+
else:
256+
cr = crAPI.get(name=cr_name)
257+
return cr
258+
except NotFoundError:
259+
logger.debug(f"CR {cr_name} of kind {cr_kind} does not exist in namespace {namespace}")
260+
261+
return {}
262+
263+
264+
def getSecret(dynClient: DynamicClient, namespace: str, secret_name: str) -> dict:
265+
"""
266+
Get a Secret
267+
"""
268+
try:
269+
secretAPI = dynClient.resources.get(api_version="v1", kind="Secret")
270+
secret = secretAPI.get(name=secret_name, namespace=namespace)
271+
logger.debug(f"Secret {secret_name} exists in namespace {namespace}")
272+
return secret.to_dict()
273+
except NotFoundError:
274+
logger.debug(f"Secret {secret_name} does not exist in namespace {namespace}")
275+
return {}
276+
277+
278+
def apply_resource(dynClient: DynamicClient, resource_yaml: str, namespace: str):
279+
"""
280+
Apply a Kubernetes resource from its YAML definition.
281+
If the resource already exists, it will be updated.
282+
If it does not exist, it will be created.
283+
"""
284+
resource_dict = yaml.safe_load(resource_yaml)
285+
kind = resource_dict['kind']
286+
api_version = resource_dict['apiVersion']
287+
metadata = resource_dict['metadata']
288+
name = metadata['name']
289+
290+
try:
291+
resource = dynClient.resources.get(api_version=api_version, kind=kind)
292+
# Try to get the existing resource
293+
resource.get(name=name, namespace=namespace)
294+
# If found, update it
295+
logger.debug(f"Updating existing {kind} '{name}' in namespace '{namespace}'")
296+
resource.patch(body=resource_dict, namespace=namespace, name=name)
297+
except NotFoundError:
298+
# If not found, create it
299+
logger.debug(f"Creating new {kind} '{name}' in namespace '{namespace}'")
300+
resource.create(body=resource_dict, namespace=namespace)
301+
302+
246303
def listInstances(dynClient: DynamicClient, apiVersion: str, kind: str) -> list:
247304
"""
248305
Get a list of instances of a particular CR on the cluster

0 commit comments

Comments
 (0)