Skip to content

Instantly share code, notes, and snippets.

@beatsandpics
Forked from yuanying/kubectl-run-with-pvc.sh
Last active September 13, 2021 06:48
Show Gist options
  • Save beatsandpics/111a0c31b74274442785da98bfb04457 to your computer and use it in GitHub Desktop.
Save beatsandpics/111a0c31b74274442785da98bfb04457 to your computer and use it in GitHub Desktop.
kubectl run with PVCs
#!/bin/bash
IMAGE="registry.begasoft.ch/base_images_public/bgstoolbox:0"
COMMAND="/bin/sh"
SUFFIX=$(date +%s | shasum | base64 | fold -w 10 | head -1 | tr '[:upper:]' '[:lower:]')
AWSKEY="none"
AWSSEC="none"
usage_exit() {
echo "Usage: $0 [-c command] [-i image] [-a <AWSKEY>:<AWSSEC>]PVC ..." 1>&2
echo ""
echo "Example to list files:"
echo "./kubectl-run-with-pvc.sh -c \"ls -al /pvcs/<pvc>\" <pvc>"
echo ""
echo "Example to copy files to S3:"
echo "./kubectl-run-with-pvc.sh -c \"aws --endpoint-url <url> s3 cp /pvcs/<pvc>/ s3://<bucket> --recursive\" -a \"<AWSKEY>:<AWSSEC>\" <pvc>"
echo ""
exit 1
}
while getopts i:c:a:h OPT
do
case $OPT in
i) IMAGE=$OPTARG
;;
c) COMMAND=$OPTARG
;;
a) AWSVAR=$OPTARG
;;
h) usage_exit
;;
\?) usage_exit
;;
esac
done
shift $(($OPTIND - 1))
VOL_MOUNTS=""
VOLS=""
COMMA=""
for i in $@
do
VOL_MOUNTS="${VOL_MOUNTS}${COMMA}{\"name\": \"${i}\",\"mountPath\": \"/pvcs/${i}\"}"
VOLS="${VOLS}${COMMA}{\"name\": \"${i}\",\"persistentVolumeClaim\": {\"claimName\": \"${i}\"}}"
COMMA=","
done
if [[ ! -z "$AWSVAR" ]]
then
AWSKEY=`echo ${AWSVAR} | awk -F ":" '{print $1}'`
AWSSEC=`echo ${AWSVAR} | awk -F ":" '{print $2}'`
fi
ARGS=`echo $COMMAND | jq -cR 'split(" ")'`
kubectl run -it --rm --restart=Never --image=${IMAGE} pvc-mounter-${SUFFIX} --overrides "
{
\"spec\": {
\"hostNetwork\": true,
\"containers\":[
{
\"args\": ${ARGS},
\"stdin\": true,
\"tty\": true,
\"name\": \"pvc\",
\"image\": \"${IMAGE}\",
\"env\": [
{\"name\": \"AWS_ACCESS_KEY_ID\",\"value\": \"${AWSKEY}\"},{\"name\": \"AWS_SECRET_ACCESS_KEY\",\"value\": \"${AWSSEC}\"}
],
\"volumeMounts\": [
${VOL_MOUNTS}
]
}
],
\"volumes\": [
${VOLS}
]
}
}
" -- ${COMMAND}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment