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 3.3k times
3 Answers
54
ssh-add - <<< "${SSH_PRIVATE_KEY}"
-
3Or since it is bash `ssh-add - <<<"${SSH_PRIVATE_KEY}"` and use a *herestring*. – David C. Rankin Sep 16 '17 at 11:06
-
1
-
12Well, 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` `<<<` to make the variable data in `"${SSH_PRIVATE_KEY}"` appear as input on `stdin` for `ssh-add` with `ssh-add - <<<"${SSH_PRIVATE_KEY}"`. It is faster in that no additional *subshells* are generated. You have 3 generated with `echo key | ssh-add -` (1-for `echo`, 1-for the pipe `|` and 1-for ssh-add). (note: you may or may not need the `'-'` after `ssh-add`, but I suspect you do.) – 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
-
23
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.yml
file:- echo "$SSH_PRIVATE_KEY" | tr -d '\r' | ssh-add - > /dev/null

Dieter Casier
- 633
- 5
- 9
6
Also, you can use:
echo "${SSH_PRIVATE_KEY}" | ssh-add -
or
ssh-add <(echo "$SSH_PRIVATE_KEY")

Magepow
- 61
- 1
- 2
-
2Thanks! This worked for me `echo "${SSH_PRIVATE_KEY}" | ssh-add - ` – Joseph Adam Oct 07 '21 at 12:58