Search code examples
apachekubectl

Run Kubectl in apache


I have this bash script:

#!/bin/bash

USERNAME=$1
WORKDIR='dir_'$USERNAME

mkdir deployment/$WORKDIR
cat deployment/deploy.yml > deployment/$WORKDIR/deploy.yml

sed -i 's/alopezfu/'$USERNAME'/g' deployment/$WORKDIR/deploy.yml

kubectl apply -f deployment/$WORKDIR/deploy.yml

rm -rf deployment/$WORKDIR/

And i use exec funcition in PHP for run.

And i get this messege in /var/log/apache/error.log

To view or setup config directly use the 'config' command. error: no configuration has been provided, try setting KUBERNETES_MASTER environment variable error: Missing or incomplete configuration info. Please point to an existing, complete config file:

  1. Via the command-line flag --kubeconfig
    1. Via the KUBECONFIG environment variable
    2. In your home directory as ~/.kube/config

I need help 🙏


Solution

  • Since you are running the script as a diferent user, you need to "tell" to kubectl where is the configuration file.

    This can be done setting the variable KUBECONFIG in your environment.

    Supposing the kubernetes config file is in the dir /var/www/ with the correct permission to be readable, you can configure your php script like this:

    <?php
    $kubeconfig = "/var/www/config"; // The config file
    
    putenv("KUBECONFIG=$kubeconfig"); // set the environment variable KUBECONFIG
    
    $output = shell_exec("KUBECONFIG=$kubeconfig ; kubectl get pods -A"); // Runs the command 
    
    echo "<pre>$output</pre>"; // and return the expected output.
    ?>
    

    Please be aware that:

    • Setting certain environment variables may be a potential security breach.

    Some actions that should mitigate the impacts:

    • Make sure your config file is safe and not reachable from the browser;

    • Consider to create a serviceAccount with limited permissions;

    Here you can find some useful commands and kubectl tips.

    How to create a service account for kubectl