Skip to content

Commit 5d17159

Browse files
author
Sanjay Prabhakar
committed
[patch] added ocp functions
1 parent 9913f14 commit 5d17159

1 file changed

Lines changed: 53 additions & 0 deletions

File tree

src/mas/devops/ocp.py

Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -242,6 +242,59 @@ def crdExists(dynClient: DynamicClient, crdName: str) -> bool:
242242
logger.debug(f"CRD does not exist: {crdName}")
243243
return False
244244

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

246299
def listInstances(dynClient: DynamicClient, apiVersion: str, kind: str) -> list:
247300
"""

0 commit comments

Comments
 (0)