Hello folks, I am trying to see if the kubernetes...
# getting-started
s
Hello folks, I am trying to see if the kubernetes namespace exists using the .get function before creating it. I am not sure about the inputs to the .get function. Say, I have a namespace already created "my-namespace". I need to check before creating the namespace with the same name. This is my current code but doesn't work. let isNamespaceExist = k8s.core.v1.Namespace.get("my-namespace"); Thanks anyway
f
Hi @some-honey-3067, Pulumi operates in a declarative way, which means that you don't need to specify imperatively what pulumi should do (do this then that) . On the contrary, it is pulumi's responsibility to determine whether the operation you're trying to accomplish can be done or not. You need only to specify what is your desired state (i.e., I wish there's a <my-namespace> namespace in my cluster). As for your code: in nodeJS/Typescript you must include the keyword
new
to invoke the Namespace class constructor, which will create, if possible, a new namespace. But in order to do that, you need to specify which cluster to use. This is usually called a provider. So your code may end up looking a bit like this:
Copy code
const nsName = 'my-namespace'
new Namespace(
  nsName,
  {
    apiVersion: 'v1',
    kind: 'Namespace',
    metadata: {
      name: nsName
    }
  },
  { provider: yourClusterInstance }
);
I hope this helps.
s
@fast-easter-23401 I know this will create a new namespace but what if the namespace already exists? Will pulumi throw an error? Thanks for replying
f
It should, as your cloud provider's API would most probably return a client error (400), since the namespace already exists.
s
My objective is to create the namespace only if it doesn't exist. Is there a way to achieve it?
f
The code snippet above can be used to this end.
s
@fast-easter-23401 i got your point. I am looking for a more dynamic solution where if the namespace exists, Pulumi shouldn't throw an error and should pass without any errors.
f
Got any chance sorting this out? A different approach is to let pulumi know that you want to create a new namespace while provisioning a new resource. But you'll get an error anyways. I guess you could create a dynamic provider for this, but quite frankly I don't see the advantage of investing so much time. Who is responsible for executing your code? Does it run locally or in a CI/CD pipeline? Good luck.
s
As a workaround, I do the following:
let createdNamespacesArray = Array();
let namespaceNamesArray = ["ns1", "ns2", "ns1", "ns3"];
for (let ns = 0; ns < namespaceNamesArray.length; ns++) {
if (!createdNamespacesArray.includes(namespaceNamesArray[ns])) {
const k8sNamespace = new k8s.core.v1.Namespace(
namespaceNamesArray[ns],
{},
{
provider: clusterInstance,
}
);
createdNamespacesArray.push(namespaceNamesArray[ns]);
}
}
This works for me but I don't like it really.