<p>It's a simple question, but I could not find a definite answer for it.</p>
<h3>Question</h3>
<p>Is it possible to create a <em>namespace</em> only if it doesn't exist.<br />
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).</p>
<p>The thing is I'm using <em>CDK</em> to deploy some basics <em>K8S</em> 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.</p>
<p>I tried <code>patch</code>, but it seems to expect the resource to exist already (i.e. it fails with <code>NotFound</code> error).</p>
<h3>Two limitations:</h3>
<ol>
<li>I can't query to see if the namespace exists or not.</li>
<li>I can't use <code>apply</code> since I don't have the exact definition of the namespace.</li>
</ol>
<p>Is there any way to achieve this?</p>

Rad
<p>i wouldn't go for any other solution except the following code snippet:</p>
<p><strong>kubernetes 1.19 and above (included)</strong></p>
<pre><code>kubectl create namespace &lt;add-namespace-here&gt; --dry-run=client -o yaml | kubectl apply -f -
</code></pre>
<p><strong>kubernetes 1.18 and below (included)</strong></p>
<pre><code>kubectl create namespace &lt;add-namespace-here&gt; --dry-run -o yaml | kubectl apply -f -
</code></pre>
<p>it creates a namespace in dry-run and outputs it as a yaml. The output will be passed as stdin to kubectl apply -f -</p>
<p>The last hyphen is important while passing kubectl to read from stdin.</p>
<p>Also see the examples in:</p>
<pre><code>kubectl apply --help
</code></pre>
