I have a bash script inside a Docker container that needs to access remote server via ssh. I have SSH key inside a variable. How can I add it to SSH?
Asked
Active
Viewed 2.2k times
3 Answers
43
ssh-add - <<< "${SSH_PRIVATE_KEY}"
-
2
-
1
-
11Well, the variable `"${SSH_PRIVATE_KEY}"` holds the value. You need it as input on `stdin` for `ssh-add`. As a convenience feature bash has both a *heredoc* and *herestring*. You can use the *herestring` `<< – David C. Rankin Sep 16 '17 at 11:45
-
2@DavidC.Rankin Yes you need the '-' or ssh-add will look for the key in $HOME/.ssh – Fabien Bouleau Sep 19 '17 at 13:34
-
This solution is not working with Paker provisioner `shell` and returning the error: `Syntax error: redirection unexpected` This is because here strings like <<< "$token" are not supported by POSIX /bin/sh Use the solution from GitLab provided by @Dieter Casier – Roman Shishkin May 22 '21 at 22:34
-
If you are trying this in GitHub Actions, you need to do `eval $(ssh-agent -s) && ssh-add - <<< '${{ secrets.SSH_PRIVATE_KEY }}'`. – Nato Boram Dec 08 '21 at 22:14
-
17
If you are using Gitlab CI/CD and you want to use a variable as an SSH key you can do the following:
- Add your variable in
Settings->CI/CD->Variables Use that variable in your
.gitlab-ci.ymlfile:- echo "$SSH_PRIVATE_KEY" | tr -d '\r' | ssh-add - > /dev/null
Dieter Casier
- 553
- 4
- 9
4
Also, you can use:
echo "${SSH_PRIVATE_KEY}" | ssh-add -
or
ssh-add <(echo "$SSH_PRIVATE_KEY")
Magepow
- 41
- 2
-
1Thanks! This worked for me `echo "${SSH_PRIVATE_KEY}" | ssh-add - ` – Joseph Adam Oct 07 '21 at 12:58