Home > Software engineering >  How to run shell script via kubectl without interactive shell
How to run shell script via kubectl without interactive shell

Time:12-02

I am trying to export a configuration from a service called keycloak by using shell script. To do that, export.sh will be run from the pipeline.

the script connects to k8s cluster and run the command in there.

So far, everything goes okay the export work perfectly.

But when I try to exit from the k8s cluster with exit and directly end the shell script. therefore it will move back to the pipeline host without staying in the remote machine.

Running the command from the pipeline

ssh -t [email protected] 'bash' < export.sh

export.sh

#!/bin/bash
set -x
set -e

rm -rf /tmp/realm-export

if [ $(ps -ef | grep "keycloak.migration.action=export" | grep -v grep | wc -l) != 0 ]; then
    echo "Another export is currently running"
    exit 1
fi

kubectl -n keycloak exec -it keycloak-0 bash

mkdir /tmp/export
/opt/jboss/keycloak/bin/standalone.sh -Dkeycloak.migration.action=export -Dkeycloak.migration.provider=dir -Dkeycloak.migration.dir=/tmp/export -Dkeycloak.migration.usersExportStrategy=DIFFERENT_FILES -Djboss.socket.binding.port-offset=100
rm /tmp/export/master-*
exit
kubectl -n keycloak cp keycloak-0:/tmp/export /tmp/realm-export
exit
exit

scp [email protected]:/tmp/realm-export/* ./configuration2/realms/

After the first exit the whole shell script stopped, the left commands doesn't work. it won't stay on [email protected]. Is there any solutions?

CodePudding user response:

Run the commands inside without interactive shell using HEREDOC(EOF).

It's not EOF. It's 'EOF'. this prevents a variable expansion in the current shell.

But in the other script's /tmp/export/master-* will expand as you expect.

kubectl -n keycloak exec -it keycloak-0 bash <<'EOF'
<put your codes here, which you type interactively>
EOF

export.sh

#!/bin/bash
set -x
set -e

rm -rf /tmp/realm-export

if [ $(ps -ef | grep "keycloak.migration.action=export" | grep -v grep | wc -l) != 0 ]; then
    echo "Another export is currently running"
    exit 1
fi

# the suggested code.
kubectl -n keycloak exec -it keycloak-0 bash <<'EOF'
<put your codes here, which you type interactively>
EOF

mkdir /tmp/export
/opt/jboss/keycloak/bin/standalone.sh -Dkeycloak.migration.action=export -Dkeycloak.migration.provider=dir -Dkeycloak.migration.dir=/tmp/export -Dkeycloak.migration.usersExportStrategy=DIFFERENT_FILES -Djboss.socket.binding.port-offset=100
rm /tmp/export/master-*

kubectl -n keycloak cp keycloak-0:/tmp/export /tmp/realm-export

scp [email protected]:/tmp/realm-export/* ./configuration2/realms/

Even if scp runs successfully or not, this code will exit.

  • Related