Kubernetes rest api to check if namespace is created and active

8/1/2016

I call the below rest api with post body to create a namespace in kubernetes

http://kuberneteshot/api/v1/namespaces/

{
    "apiVersion": "v1",
    "kind": "Namespace",
    "metadata": {
        "name": "testnamespace"
    }
}

In response i get the http status 201 created and the below json response

{
    "kind": "Namespace",
    "apiVersion": "v1",
    "metadata": {
        "name": "testnamespace",
        "selfLink": "/api/v1/namespaces/testnamespace",
        "uid": "701ff75e-5781-11e6-a48a-74dbd1a0fb73",
        "resourceVersion": "57825525",
        "creationTimestamp": "2016-08-01T00:46:52Z",
    },
    "spec": {
        "finalizers": [
            "kubernetes"
        ]
    },
    "status": {
        "phase": "Active"
    }
}

Does the status in response with phase as Active mean the namespace is successfully created and active ?

Is there any other rest api to check if the namespace exists and is active ?

The reason i would like to know if the namespace is created is because i get an error message if i fire create pod before the namespace is actually created:

Error from server: error when creating "./pod.json": pods "my-pod" is forbidden: service account username/default was not found, retry after the service account is created

The below works fine if i give a sleep of 5 seconds between create namespace and create pod command

kubectl delete namespace testnamepsace;kubectl create namespace testnamepsace;sleep 5;kubectl create -f ./pod.json --namespace=testnamepsace

If i don't give the sleep of 5 seconds i see the error message mentioned above

-- nfsquake
kubernetes

2 Answers

8/1/2016

Yes, the namespace is persisted prior to being returned from the create API call. The returned object shows the status of the namespace as Active.

You can also do GET http://kubernetehost/api/v1/namespaces/testnamespace to retrieve the same information.

-- Jordan Liggitt
Source: StackOverflow

8/1/2016

Apparently your Pod has a hard dependency on the default ServiceAccount, so you probably want to check it's been created instead of looking only at the namespace state. The existence of the namespace doesn't guarantee the immediate availability of your default ServiceAccount.

Some API endpoints you might want to query:

  • GET /api/v1/namespaces/foo/serviceaccounts/default
    returns 200 with the object description if the ServiceAccount default exists in the namespace foo, 404 otherwise

  • GET /api/v1/serviceaccounts?fieldSelector=metadata.namespace=foo,metadata.name=default
    returns 200 and a list of all ServiceAccount items in the namespace foo with name default (empty list if no object matches)

-- Antoine Cotten
Source: StackOverflow