I have a script.sh
file which checks for loaded SSH agent and adds a key.
If I run this script directly, it works but if I run it via some worker it doesn't unless I do those changes:
This works:
#!/bin/bash -e
printf "<<<<< Start SSH agent and Github deploy key >>>>>\n"
if ps -p $SSH_AGENT_PID > /dev/null
then
printf "<<<<< ssh-agent is already running >>>>>\n"
else
eval `ssh-agent -s`
fi
ssh-add $deploy_key_path
But his doesn't work:
#!/bin/bash -e
if [ $(ps ax | grep [s]sh-agent | wc -l) -gt 0 ] ; then
printf "<<<<< ssh-agent is already running >>>>>\n"
else
eval `ssh-agent -s`
fi
ssh-add $deploy_key_path
The error says ...failed. Exit Code: 2(Misuse of shell builtins)..
which happens at the line ssh-add $deploy_key_path
When checking the reserved Bash error codes I see:
2 Misuse of shell builtins empty_function() {} Missing keyword or command
CodePudding user response:
Here is one way I'd use ssh-agent
and ssh-add
in a reasonable way without compromising security too much. (not keeping keys unlocked more than it is strictly required).
#!/usr/bin/env sh
# Do not leave key unlocked after execution of this script
trap 'ssh-add -d "$deploy_key_path"' EXIT INT
# If ssh-agent has an auth socket or has a PID
if [ -S "$SSH_AUTH_SOCK" ] || [ "$((SSH_AGENT_PID))" -gt 0 ] ; then
printf '<<<<< ssh-agent is already running >>>>>\n'
else
# Do not use back-ticks as it is legacy obsolete
eval "$(ssh-agent -s)"
fi
# Do not leave key unlocked more than 5 minutes
ssh-add -t 600 "$deploy_key_path"