Skip to content
Snippets Groups Projects

kubectl-create-config

  • Clone with SSH
  • Clone with HTTPS
  • Embed
  • Share
    The snippet can be accessed without any authentication.
    Authored by Tibo

    Create a kubeconfig file that you can use with kubectl.

    To create a kubeconfig.yaml:

    kubectl-create-config.php --name username --namespace default > kubeconfig.yaml

    To use the created kubeconfig:

    kubectl --kubeconfig kubeconfig.yaml version
    kubectl --kubeconfig kubeconfig.yaml get pod
    Edited
    kubectl-create-config.php 1.53 KiB
    #!/bin/php
    
    <?php
    #
    # kubectl-create-conf.php
    # A PHP script that creates a Service Account and extracts to corresponding
    # token to create a kubeconfig.yaml file
    # https://cylab.be/blog/178/create-and-use-kubeconfigyaml
    # https://gitlab.cylab.be/-/snippets/1
    #
    $options = getopt("", ["name:", "namespace:"]);
    
    // NAME and NAMESPACE
    $NAMESPACE = $options["namespace"];
    $NAME = $options["name"];
    
    // SERVICE ACCOUNT and TOKEN
    $tmpl = <<<EOT
    apiVersion: v1
    kind: ServiceAccount
    metadata:
      name: $NAME
    EOT;
    $cmd = "echo '$tmpl' | kubectl apply --namespace $NAMESPACE -f -";
    $out = shell_exec($cmd);
    
    $cmd = "kubectl get sa $NAME --namespace $NAMESPACE -o json";
    $out = shell_exec($cmd);
    $json = json_decode($out, true);
    $secret_name = $json["secrets"][0]["name"];
    
    $cmd = "kubectl get secret $secret_name --namespace $NAMESPACE -o json";
    $out = shell_exec($cmd);
    $json = json_decode($out, true);
    $TOKEN = base64_decode($json["data"]["token"]);
    
    // SERVER and CERTIFICATE
    $cmd = "kubectl config view --flatten -o json";
    $out = shell_exec($cmd);
    $json = json_decode($out, true);
    
    $SERVER = $json["clusters"][0]["cluster"]["server"];
    $CERTIFICATE = $json["clusters"][0]["cluster"]["certificate-authority-data"];
    
    // TEMPLATE
    $conf = <<<EOT
    apiVersion: v1
    kind: Config
    users:
    - name: $NAME
      user:
        token: $TOKEN
    clusters:
    - name: k8s
      cluster:
        certificate-authority-data: $CERTIFICATE
        server: $SERVER
    contexts:
    - name: $NAME@$NAMESPACE
      context:
        cluster: k8s
        user: $NAME
        namespace: $NAMESPACE
    current-context: $NAME@$NAMESPACE
    
    EOT;
    
    echo $conf;
    0% Loading or .
    You are about to add 0 people to the discussion. Proceed with caution.
    Finish editing this message first!
    Please register or to comment