It's a simple question, but I could not find a definite answer for it.
Question
Is it possible to create a namespace only if it doesn't exist.
My objective is to create some service accounts without caring if their namespaces exist or not (if not, then they should be created on the fly).
The thing is I'm using CDK to deploy some basics K8S resources (including service accounts). To safely do this, I need to make sure the namespace (given in the service account manifest) already exists. However I'm not able to find any solution.
I tried patch, but it seems to expect the resource to exist already (i.e. it fails with NotFound error).
Two limitations:
- I can't query to see if the namespace exists or not.
- I can't use
applysince I don't have the exact definition of the namespace.
Is there any way to achieve this?
Given the limitations I can only think of one way which is to apply a namespace yaml always before you apply the service account yaml. If the namespace exists already it will give you a message that
namespace already exists.You can ignore that message and move ahead.So here we are being declarative and it does not matter what exists and what does not. You just define what the desired state should look like and kubernetes will take care of making sure that happens.