How do I best determine if a manifest already exists?
flickerfly opened this issue · 2 comments
I'd like to determine if a ConfigMap already exists before I create it so I can take appropriate actions. How do I accomplish this?
Here is the code I've tried:
#!/usr/bin/env python3
import os
import sys
import yaml
from kubernetes import client, config
from openshift.dynamic import DynamicClient
import openshift.dynamic.exceptions
# Check if code is running in OpenShift
if "OPENSHIFT_BUILD_NAME" in os.environ:
config.load_incluster_config()
file_namespace = open(
"/run/secrets/kubernetes.io/serviceaccount/namespace", "r"
)
if file_namespace.mode == "r":
namespace = file_namespace.read()
print("namespace: %s\n" %(namespace))
else:
config.load_kube_config()
# Configure cluster access
k8s_config = client.Configuration()
k8s_client = client.api_client.ApiClient(configuration=k8s_config)
dyn_client = DynamicClient(k8s_client)
v1_configmaps = dyn_client.resources.get(api_version='v1', kind='ConfigMap')
cm_name = "rh-operators-not-here"
cm_namespace = "operator-lifecycle-manager"
try:
configmap_list = v1_configmaps.get(namespace=cm_namespace,name=cm_name)
except 'NotFoundError':
print("WARNING: ConfigMap " + cm_name + " not found in namespace " + cm_namespace + ". We will create it.")
pass
except 'kubernetes.client.rest.ApiException':
print("apiexception")
pass
except NameError:
print("nameerror")
pass
except:
print("Unexpected error:", sys.exc_info()[0])
raise
When I run that, twice I get "During handling of the above exception, another exception occurred" and then all the output ends in "TypeError: catching classes that do not inherit from BaseException is not allowed".
How do I properly catch this so I can determine if I should .create or .replace it?
except 'NotFoundError':
should be except NotFoundError:
, the issue is that you have catch <string>
instead of catch <Exception>
.
This code should work
from openshift.dynamic.exceptions import NotFoundError, DynamicApiError
<snip>
try:
configmap_list = v1_configmaps.get(namespace=cm_namespace,name=cm_name)
except NotFoundError:
print("WARNING: ConfigMap " + cm_name + " not found in namespace " + cm_namespace + ". We will create it.")
pass
except DynamicApiError:
print("apiexception")
pass
<snip>
Thank you @fabianvf ! Your example was extremely helpful.
I had tried it as an Exception, that was just some last-ditch efforts lingering. What I hadn't figured out was the proper import!