Last active
April 8, 2023 21:31
-
-
Save dominiwe/41fd574eb9a7e28c8b2ee9e10c70aefe to your computer and use it in GitHub Desktop.
A script which generates information to use ssh in a ci/cd pipeline.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/env bash | |
set -euo pipefail | |
if [ $# -eq 0 ] || [ "$1" = "-h" ] || [ "$1" = "--help" ]; then | |
echo -e "This script takes a hostname as its only argument. | |
It will get the host key and print a base64 encoding of it to be used in a CI/CD variable. | |
It will also generate a new ssh key pair and print: | |
1. The public key (add it on the server manually). | |
2. A base64 encoding of the private key (to be used as a CI/CD variable). | |
\e[0;31mKeep in mind: | |
1. It will only print this information once! It is not stored anywhere! | |
2. It will NOT automatically add the public key to the server! Do this manually! | |
\e[0;0m | |
Use this script in the following way (specify a host): | |
\e[0;34m$0 host\e[0;0m | |
" | |
exit 1 | |
fi | |
# The host as specified to the script | |
HOST="$1" | |
# Temporary data | |
TEMPDIR=$(mktemp -d) | |
trap 'rm -rf -- "$TEMPDIR"' EXIT | |
echo -e " | |
Created temporary directory \e[0;33m$TEMPDIR\e[0;0m | |
It will only persist if this script is killed with \e[0;31msigkill\e[0;0m! | |
In that case, \e[0;34mplease run \e[0;0m\`\e[0;33mrm -rf $TEMPDIR\e[0;0m\`\e[0;34m manually for security reasons\e[0;0m!" | |
if ! ssh -q -o StrictHostKeyChecking=accept-new -o UserKnownHostsFile="$TEMPDIR/known_hosts" "$HOST" 'exit'; then | |
echo "Could not connect to host...." | |
exit 1 | |
fi | |
HOSTKEY=$(head -1 "$TEMPDIR/known_hosts" | base64 -w0) | |
echo -e "\e[0;31m | |
Base64 encoded host key for host \e[0;33m$HOST\e[0;31m: | |
\e[0;0m" | |
echo "$HOSTKEY" | |
ssh-keygen -C "gitlab_pipelines" -q -N "" -t ed25519 -f "$TEMPDIR/id" | |
PRIVATEKEY=$(base64 -w0 <"$TEMPDIR/id") | |
PUBLICKEY=$(cat "$TEMPDIR/id.pub") | |
echo -e "\e[0;31m | |
Base64 encoded generated ssh private key: | |
\e[0;0m" | |
echo "$PRIVATEKEY" | |
echo -e "\e[0;31m | |
Generated ssh public key in plaintext: | |
\e[0;0m" | |
echo "$PUBLICKEY" | |
echo "" && exit 0 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment