- Notifications
You must be signed in to change notification settings - Fork286
GitHub Action to setup `ssh-agent` with a private key
License
webfactory/ssh-agent
Folders and files
| Name | Name | Last commit message | Last commit date | |
|---|---|---|---|---|
Repository files navigation
This action
- starts the
ssh-agent, - exports the
SSH_AUTH_SOCKenvironment variable, and - loads one or several private SSH key into the agent.
It should work in all GitHub Actions virtual environments, including container-based workflows.
Windows and Docker support is, however, somewhat new. Since we have little feedback from the field, things might not run so smooth for you as we'd hope. If Windows and/or Docker-based workflows work well for you, leave a 👍 at#17.
Also, using multiple GitHub deployment keys is supported; keys are mapped to repositories by using SSH key comments (see below).
When running a GitHub Action workflow to stage your project, run tests or build images, you might need to fetch additional libraries orvendors from private repositories.
GitHub Actions only have access to the repository they run for. So, in order to access additional private repositories, create an SSH key with sufficient access privileges. Then, use this action to make the key available withssh-agent on the Action worker node. Once this has been set up,git clone commands usingssh URLs willjust work. Also, runningssh commands to connect to other servers will be able to use the key.
- Generate a new SSH key with sufficient access privileges. For security reasons, don't use your personal SSH key but set up a dedicated one for use in GitHub Actions. See below for a few hints if you are unsure about this step.
- Make sure you don't have a passphrase set on the private key.
- Add the public SSH key to the private repository you are pulling from during the Github Action as a 'Deploy Key'.
- Add the private SSH key to the repository triggering the Github Action:
- In your repository, go to theSettings > Secrets menu and create a new secret. In this example, we'll call it
SSH_PRIVATE_KEY. - Put the contents of theprivate SSH key file into the contents field.
- This key should start with
-----BEGIN ... PRIVATE KEY-----, consist of many lines and ends with-----END ... PRIVATE KEY-----.
- In your repository, go to theSettings > Secrets menu and create a new secret. In this example, we'll call it
- In your workflow definition file, add the following step. Preferably this would be rather on top, near the
actions/checkout@v4line.
# .github/workflows/my-workflow.ymljobs:my_job:...steps: -uses:actions/checkout@v4# Make sure the @v0.9.0 matches the current version of the action -uses:webfactory/ssh-agent@v0.9.0with:ssh-private-key:${{ secrets.SSH_PRIVATE_KEY }}# ... other steps
- If, for some reason, you need to change the location of the SSH agent socket, you can use the
ssh-auth-sockinput to provide a path.
There are cases where you might need to use multiple keys. For example, "deploy keys" might be limited to a single repository, so you'll need several of them.
You can set up different keys as different secrets and pass them all to the action like so:
# ... contents as before -uses:webfactory/ssh-agent@v0.9.0with:ssh-private-key:| ${{ secrets.FIRST_KEY }} ${{ secrets.NEXT_KEY }} ${{ secrets.ANOTHER_KEY }}
Thessh-agent will load all of the keys and try each one in order when establishing SSH connections.
There's onecaveat, though: SSH servers may abort the connection attempt after a number of mismatching keys have been presented. So if, for example, you have six different keys loaded into thessh-agent, but the server aborts after five unknown keys, the last key (which might be the right one) will never even be tried. But when you're using GitHub Deploy Keys, read on!
When usingGithub deploy keys, GitHub servers will accept thefirst known key. But since deploy keys are scoped to a single repository, this might not be the key needed to access a particular repository. Thus, you will get the error messagefatal: Could not read from remote repository. Please make sure you have the correct access rights and the repository exists. if the wrong key/repository combination is tried.
To support picking the right key in this use case, this action scanskey comments and will set up extra Git and SSH configuration to make things work.
- When creating the deploy key for a repository like
git@github.com:owner/repo.gitorhttps://github.com/owner/repo, put that URL into the key comment. (Hint: Tryssh-keygen ... -C "git@github.com:owner/repo.git".) - After keys have been added to the agent, this action will scan the key comments.
- For key comments containing such URLs, a Git config setting is written that uses
url.<base>.insteadof. It will redirectgitrequests to URLs starting with eitherhttps://github.com/owner/repoorgit@github.com:owner/repoto a fake hostname/URL likegit@...some.hash...:owner/repo. - An SSH configuration section is generated that applies to the fake hostname. It will map the SSH connection back to
github.com, while at the same time pointing SSH to a file containing the appropriate key's public part. That will make SSH use the right key when connecting to GitHub.com.
The following inputs can be used to control the action's behavior:
ssh-private-key: Required. Use this to provide the key(s) to load as GitHub Actions secrets.ssh-auth-sock: Can be used to control where the SSH agent socket will be placed. Ultimately affects the$SSH_AUTH_SOCKenvironment variable.log-public-key: Set this tofalseif you want to suppress logging ofpublic key information. To simplify debugging and since it contains public key information only, this is turned on by default.ssh-agent-cmd: Optional. Use this to specify a custom location for thessh-agentbinary.ssh-add-cmd: Optional. Use this to specify a custom location for thessh-addbinary.git-cmd: Optional. Use this to specify a custom location for thegitbinary.
The action exports theSSH_AUTH_SOCK andSSH_AGENT_PID environment variables through the Github Actions core module.The$SSH_AUTH_SOCK is used by several applications like git or rsync to connect to the SSH authentication agent.The$SSH_AGENT_PID contains the process id of the agent. This is used to kill the agent in post job action.
Since each jobruns in a fresh instance of the virtual environment, the SSH key will only be available in the job where this action has been referenced. You can, of course, add the action in multiple jobs or even workflows. All instances can use the sameSSH_PRIVATE_KEY secret.
If the private key is not in thePEM format, you will see anError loading key "(stdin)": invalid format message.
Usessh-keygen -p -f path/to/your/key -m pem to convert your key file toPEM, but be sure to make a backup of the file first 😉.
If you know that your favorite tool or platform of choice requires extra tweaks or has some caveats when running with SSH, feel free to open a PR to amend this section here.
If you are using this action on container-based workflows, make sure the container has the necessary SSH binaries or package(s) installed.
When you are building Docker images withdocker build ordocker compose build and need to provide the SSH keys to the build, don't forget to pass--ssh default=${{ env.SSH_AUTH_SOCK }} on the command line to pass the SSH agent socket through. See theDocker documentation for more information on this option.
If you are using thedocker/build-push-action, you can do so by adding the following config.
-name:Build and pushid:docker_builduses:docker/build-push-action@v2with:ssh:| default=${{ env.SSH_AUTH_SOCK }}
Make sure not to miss the next section, though.
When you pass the SSH agent socket to the Docker build environmentand want to use multiple GitHub deploy keys, you need to copy the Git and SSH configuration files to the build environment as well. This is necessaryin addition to forwarding the SSH agent socket into the build process. The config files are required so that Git can pick the right one from your deployment keys.
This requires an additional step in the workflow fileafter thessh-agent step andbefore the Docker build step. You also need two additional lines in theDockerfile to actually copy the configs.
The following example will:
- collect the necessary Git and SSH configuration files in a directory that must be part of the Docker build context so that...
- ... the files can be copied into the Docker image (or an intermediate build stage).
Workflow:
-name:ssh-agent setup... -name:Collect Git and SSH config files in a directory that is part of the Docker build contextrun:| mkdir root-config cp -r ~/.gitconfig ~/.ssh root-config/ -name:Docker build# build-push-action | docker [compose] build | etc....
Dockerfile:
# Copy the two files in place and fix different path/locations inside the Docker imageCOPY root-config /root/RUN sed's|/home/runner|/root|g' -i.bak /root/.ssh/config
Keep in mind that the resulting Docker image now might contain these customized Git and SSH configuration files! Your private SSH keys are never written to files anywhere, just loaded into the SSH agent and forwarded into the container. The config files might, however, give away details about your build or development process and contain the names and URLs of your (private) repositories. You might want to use a multi-staged build to make sure these files do not end up in the final image.
If you still get the error message:fatal: Could not read from remote repository. Please make sure you have the correct access rights and the repository exists., you most likely forgot one of the steps above.
If you are using private repositories in your dependencies like this:
stuff = { git = "ssh://git@github.com/myorg/stuff.git", branch = "main" }... you will need to change a configuration in the workflow for Windows machines in order to make cargo able to clone private repositories.
There are 2 ways you can achieve this:
- Add this step once in your jobbefore any cargo command:
- name: Update cargo config to use Git CLI run: Set-Content -Path $env:USERPROFILE\.cargo\config.toml "[net]`ngit-fetch-with-cli = true"This will configure Cargo to use the Git CLI as explained in theCargo's documentation.
- Alternatively you can set it to the environment variables for the entire workflow:
env: CARGO_NET_GIT_FETCH_WITH_CLI: truexcodebuild by default uses Xcode's built-in Git tooling. If you want to use GitHub Deploy Keys as supported by this action, however, that version of Git will lack the necessary URL remapping. In this case, pass-scmProvider system to thexcodebuild command, as mentioned inApple's documentation.
The following items are not issues, but beyond what this Action is supposed to do.
When usingssh to connect from the GitHub Action worker node to another machine, youcan forward the SSH Agent socket and use your private key on the other (remote) machine. However, this Action will not configureknown_hosts or other SSH settings on the remote machine for you.
This Action is designed to pass the SSH key directly intossh-agent; that is, the key is available in memory on the GitHub Action worker node, but never written to disk. As a consequence, youcannot pass the key as a build argument or a mounted file into Docker containers that you build or run on the worker node. Youcan, however, mount thessh-agent Unix socket into a Docker container that yourun, set up theSSH_AUTH_SOCK env var and then use SSH from within the container (see#11).
If you want to usessh-keyscan to add additional hosts (that you own/know) to theknown_hosts file, you can do so with a single shell line in your Action definition. You don't really need this Action to do this for you.
As a side note, usingssh-keyscan without proper key verification is susceptible to man-in-the-middle attacks. You might prefer putting yourknown SSH host key in your own Action files to add it to theknown_hosts file. The SSH host key is not secret and can safely be committed into the repo.
In order to create a new SSH key, runssh-keygen -t ed25519 -a 100 -f path/to/keyfile, as suggested inthis blog post.If you need to work with some older server software and need RSA keys, tryssh-keygen -t rsa -b 4096 -o -f path/to/keyfile instead.
Both commands will prompt you for a key passphrase and save the key inpath/to/keyfile.In general, having a passphrase is a good thing, since it will keep the key encrypted on your disk. When using the key with this action, however, you need to make sure you don'tspecify a passphrase: The key must be usable without reading the passphrase from input. Since the key itself is stored using GitHub's "Secret" feature, it should be fairly safe anyway.
To actually grant the SSH key access, you can – on GitHub – use at least two ways:
Deploy keys can be added to individual GitHub repositories. They can give read and/or write access to the particular repository. When pulling a lot of dependencies, however, you'll end up adding the key in many places. Rotating the key probably becomes difficult. The deploy key needs to be added to the private repository that is being fetched as a private dependency.
Amachine user can be used for more fine-grained permissions management and have access to multiple repositories with just one instance of the key being registered. It will, however, count against your number of users on paid GitHub plans.
As a note to my future self, in order to work on this repo:
Clone it
Run
yarn installto fetch dependencieshack hack hack
node index.js. Inputs are passed throughINPUT_env vars with their names uppercased.On *nix use:
env"INPUT_SSH-PRIVATE-KEY=\`cat file\`" node index.jsOn Windows (cmd):
set /PINPUT_SSH-PRIVATE-KEY=< filenode index.js
On Windows (PowerShell):
${env:INPUT_SSH-PRIVATE-KEY}=(Get-Content .\test-keys -Raw);nodeindex.jsnodeindex.js
Run
npm run buildto updatedist/*, which holds the files actually runReadhttps://help.github.com/en/articles/creating-a-javascript-action if unsure.
Maybe update the README example when publishing a new version.
This action was written by webfactory GmbH, Bonn, Germany. We're a software developmentagency with a focus on PHP (mostlySymfony). If you're adeveloper looking for new challenges, we'd like to hear from you!
Copyright 2019 – 2023 webfactory GmbH, Bonn. Code released underthe MIT license.
About
GitHub Action to setup `ssh-agent` with a private key
Topics
Resources
License
Uh oh!
There was an error while loading.Please reload this page.
Stars
Watchers
Forks
Packages0
Uh oh!
There was an error while loading.Please reload this page.