26

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?

  • 1
    How did the key get in the variable in the first place? You might want to skip that step and have `ssh-add` read directly from the original file. – chepner Sep 16 '17 at 12:23
  • 3
    In my particular case SSH key is a GitLab secret variable. –  Sep 16 '17 at 14:50

3 Answers3

54
ssh-add - <<< "${SSH_PRIVATE_KEY}"
  • 3
    Or since it is bash `ssh-add - <<<"${SSH_PRIVATE_KEY}"` and use a *herestring*. – David C. Rankin Sep 16 '17 at 11:06
  • 1
    Is it faster? And why `<<<`? What about `ssh-add - < "${SSH_PRIVATE_KEY}"`? –  Sep 16 '17 at 11:30
  • 12
    Well, 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
  • Not working in Bash 5: `Error loading key "(stdin)": invalid format` – Liso Mar 10 '22 at 04:34
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

Gitlab documentation

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