How I create new namespace in Kubernetes

后端 未结 3 571
星月不相逢
星月不相逢 2021-02-03 20:44

I work in a multi-tenant node app, I know to create a new namespace in Kubernetes is possible to run a kubectl command as follow: kubectl create namespace

3条回答
  •  遇见更好的自我
    2021-02-03 21:33

    It could be as simple as calling from a shell in your app:

    kubectl create namespace 
    

    Essentially, kubectl talks to the kube-apiserver.

    You can also directly call the kube-apiserver. This is an example to list the pods:

    $ curl -k -H 'Authorization: Bearer ' \
                  https://$KUBERNETES_SERVICE_HOST:6443/api//namespaces/default/pods
    

    More specifically to create a namespace:

    $ curl -k -H -X POST -H 'Content-Type: application/json' \
                         -H 'Authorization: Bearer ' \
                         https://$KUBERNETES_SERVICE_HOST:6443/api/v1/namespaces/ -d '
    {
        "apiVersion": "v1",
        "kind": "Namespace",
        "metadata": {
            "name": "mynewnamespace"
        }
    }'
    

    In case you are wondering about the , it's a Kubernetes Secret typically belonging to a ServiceAccount and bound to a ClusterRole that allows you to create namespaces.

    You can create a Service Account like this:

    $ kubectl create serviceaccount namespace-creator
    

    Then you'll see the token like this (a token is automatically generated):

    $ kubectl describe sa namespace-creator
    Name:                namespace-creator
    Namespace:           default
    Labels:              
    Annotations:         
    Image pull secrets:  
    Mountable secrets:   namespace-creator-token-xxxxx
    Tokens:              namespace-creator-token-xxxxx
    Events:              
    

    Then you would get the secret:

    $ kubectl describe secret namespace-creator-token-xxxxx
    Name:         namespace-creator-token-xxxx
    Namespace:    default
    Labels:       
    Annotations:  kubernetes.io/service-account.name: namespace-creator
                  kubernetes.io/service-account.uid: 
    
    Type:  kubernetes.io/service-account-token
    
    Data
    ====
    ca.crt:     1025 bytes
    namespace:  7 bytes
    token:       <== This is the token you need for Authorization: Bearer
    

    Your ClusterRole should look something like this:

    kind: ClusterRole
    apiVersion: rbac.authorization.k8s.io/v1
    metadata:
      name: namespace-creator
    rules:
    - apiGroups: ["*"]
      resources: ["namespaces"]
      verbs: ["create"]
    

    Then you would bind it like this:

    $ kubectl create clusterrolebinding namespace-creator-binding --clusterrole=namespace-creator --serviceaccount=namespace-creator
    

    When it comes to writing code you can use any HTTP client library in any language to call the same endpoints.

    There are also libraries like the client-go library that takes care of the plumbing of connecting to a kube-apiserver.

提交回复
热议问题