Coder Social home page Coder Social logo

shimataro / ssh-key-action Goto Github PK

View Code? Open in Web Editor NEW
551.0 9.0 81.0 13.11 MB

GitHub Action that installs SSH key to .ssh

Home Page: https://github.com/marketplace/actions/install-ssh-key

License: MIT License

TypeScript 61.71% Shell 38.29%
github-actions ssh-key

ssh-key-action's Introduction

Install SSH Key

Build Windows macOS Ubuntu Docker container (Ubuntu) Docker container (CentOS) Docker container (Alpine Linux) Release License Stars

This action installs SSH key in ~/.ssh.

Useful for SCP, SFTP, and rsync over SSH in deployment script.

tested on:

Usage

Add your SSH key to your product secrets by clicking Settings - Secrets - Add a new secret beforehand.

PEM(RSA), PKCS8, and RFC4716(OpenSSH) formats are OK.

runs-on: ubuntu-latest
steps:
- name: Install SSH key
  uses: shimataro/ssh-key-action@v2
  with:
    key: ${{ secrets.SSH_KEY }}
    name: id_rsa # optional
    known_hosts: ${{ secrets.KNOWN_HOSTS }}
    config: ${{ secrets.CONFIG }} # ssh_config; optional
    if_key_exists: fail # replace / ignore / fail; optional (defaults to fail)
- name: rsync over SSH
  run: rsync -r ./foo/ user@remote:bar/

See Workflow syntax for GitHub Actions for details.

NOTE:

  • Server key of github.com will be always set to known_hosts.
  • SSH keys will be removed at the end of workflow.

Install multiple keys

If you want to install multiple keys, call this action multiple times. It is useful for port forwarding.

NOTE: When this action is called multiple times, the contents of known_hosts and config will be appended. key must be saved as different name, by using name option.

runs-on: ubuntu-latest
steps:
- name: Install SSH key of bastion
  uses: shimataro/ssh-key-action@v2
  with:
    key: ${{ secrets.SSH_KEY_OF_BASTION }}
    name: id_rsa-bastion
    known_hosts: ${{ secrets.KNOWN_HOSTS_OF_BASTION }}
    config: |
      Host bastion
        HostName xxx.xxx.xxx.xxx
        User user-of-bastion
        IdentityFile ~/.ssh/id_rsa-bastion
- name: Install SSH key of target
  uses: shimataro/ssh-key-action@v2
  with:
    key: ${{ secrets.SSH_KEY_OF_TARGET }}
    name: id_rsa-target
    known_hosts: ${{ secrets.KNOWN_HOSTS_OF_TARGET }} # will be appended to existing .ssh/known_hosts
    config: |                                         # will be appended to existing .ssh/config
      Host target
        HostName yyy.yyy.yyy.yyy
        User user-of-target
        IdentityFile ~/.ssh/id_rsa-target
        ProxyCommand ssh -W %h:%p bastion
- name: SCP via port-forwarding
  run: scp ./foo/ target:bar/

Q&A

SSH failed even though key has been installed.

Check below:

  • Host key verification failed.:
    • Set known_hosts parameter correctly (use ssh-keyscan command).

I want to replace/ignore key if exists.

Use if_key_exists parameter.

  • replace: replaces key
  • ignore: does nothing
  • fail: fails (default)

How do I use encrypted SSH key?

This action doesn't support encrypted key directly. Here are some solutions:

  • decrypting key beforehand: best bet, and works on any VM
  • sshpass command: next best bet, but not supported on Windows
  • expect command: be careful not to expose passphrase to console
  • SSH_ASKPASS environment variable: might be troublesome

Which one is the best way for transferring files, "direct SCP/SFTP/rsync" or "SCP/SFTP/rsync via bastion"?

I recommend rsync via bastion.

rsync -r -e "ssh bastion ssh" ./foo/ target:bar/

It has some advantages over other methods:

  • "Rsync via bastion" doesn't require to update workflow files and secrets even if it is necessary to transfer files to multiple servers.
    • Other methods require to update known_hosts if servers have changed.
  • Rsync:
    • is fastest of all.
    • does NOT break files even if disconnected during transferring.
    • can remove files that don't exist on server.
  • SCP is deprecated by OpenSSH due to outdated and inflexible protocol.
  • Using bastion is more secure because:
    • it is not necessarily to expose SSH port on servers to public.
      • Address filtering is less effective.
      • Because Azure address range is very wide.
      • And will be updated continuously.
    • if security incident ―e.g., private key leaked― occurs, it's OK just to remove authorized_keys on bastion.

I want to omit known_hosts.

First of all, you have to understand that it is NOT secure to SSH with no known_hosts and using StrictHostKeyChecking=no option.

Why do you want to omit it? If the reason is "I'm not understanding about the function of known_hosts" or "It's bother to fetch server key", you should not omit. If "It is hard to prefetch server key because the server will be created dynamically", you can use bastion server.

"known_hosts is unnecessary because I'm using secure method for SSH, such as SSHFP and signed server key." — OK, here is a special value to omit known_hosts. You should use it ONLY IF you are using secure methods... It is known_hosts: unnecessary.

License

The scripts and documentation in this project are released under the MIT License

Changelog

See CHANGELOG.md.

ssh-key-action's People

Contributors

dependabot[bot] avatar shimataro avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

ssh-key-action's Issues

OCI runtime exec failed

Hi, i get an error by executing your action

Run shimataro/ssh-key-action@v1
/usr/bin/docker exec  f95957ffde037ecbb3303b15ac3db65e1d8d2718d7019101192d2ecc4cd2163b sh -c "cat /etc/*release | grep ^ID"
OCI runtime exec failed: exec failed: container_linux.go:380: starting container process caused: exec: "/__e/node12_alpine/bin/node": stat /__e/node12_alpine/bin/node: no such file or directory: unknown

Known hosts should be optional

I'm using this action to deploy my server. Some of my deploys require sshing onto the instance. That's the only reason I need this action and I don't know the IP of my server before I create it, therefore I have nothing to pass to known_hosts. It seems a valid use case, so it seems like making the parameter optional makes sense.

Update Node.js warning

Hello,

When running a workflow containing the shimataro/ssh-key-action@v2, I receive the following warning:

Node.js 12 actions are deprecated. For more information see: https://github.blog/changelog/2022-09-22-github-actions-all-actions-will-begin-running-on-node16-instead-of-node12/. Please update the following actions to use Node.js 16: shimataro/ssh-key-action

Deleting .ssh directory on self hosted runner is terrible

Latest modifications to delete .ssh directory by default result in directory being deleted on self-hosted runner, removing remote access to server if any pre-existing SSH configuration such as authorized_hosts is present.

Please revoke change, or at least put behind a feature whose default value is to preserve the original settings.

Host Key Verification Failed (bitbucket)

I have a package hosted in a private bitbucket repository and I'm using your script the following way:
- name: Install SSH key uses: shimataro/ssh-key-action@v2 with: key: ${{ secrets.BITBUCKET_ACCESS_KEY }} known_hosts: ${{ secrets.KNOWN_HOSTS }}

and KNOWN_HOST value is:
bitbucket.org ssh-rsa AAAAB3NzaC1yc2EAAAABIwAAAQEAubiN81eDcafrgMeLzaFPsw2kNvEcqTKl/VqLat/MaB33pZy0y3rJZtnqwR2qOOvbwKZYKiEO1O6VqNEBxKvJJelCq0dTXWT5pbO2gDXC6h6QDXCaHo6pOHGPUy+YBaGQRGuSusMEASYiWunYN0vCAI8QaXnWMXNMdFP3jHAJH0eDsoiGnLPBlBp4TNm6rYI74nMzgz3B9IikW4WVK+dc8KZJZWYjAuORU3jc1c/NPskD2ASinf8v3xnfXeukU0sJ5N6m5E8VLjObPEO+mN2t/FZTMZLiFqPWc/ALSqnMnnhwrNi2rbfg/rd/IpL8Le3pSBne8+seeFVBoGqzHM9yXw==

However, yarn install always fails with "Host Key Verification Failed".

(I went reading #56 but still the same)

Feature Request: Allow multiple keys to be setup for a single remote host

Hi and thank you for your useful tool,

I have stumbled on a setup that maybe cannot be covered by your tool or any similar. GitHub does not allow to have a single SSH Deploy Key for all your projects, you are forced to create a pair per project. If you want now to use 2 projects on a GitHub Action, it is not possible to define more than one key on the same host (github.com in our case) like this:

name: Multiple SSH keys in one host
on:
  push:
    branches:
      - develop
jobs:
  test:
    runs-on: ubuntu-latest
    container:
      image: python:3.9-bullseye
    steps:
      - name: NodeJS installation
        shell: bash
        run: apt update && apt install --assume-yes nodejs
      - name: GitHub SSH Authentication for Project 1
        uses: shimataro/ssh-key-action@v2
        with:
          key: ${{ secrets.SSH_PRIVATE_KEY_PROJECT_1}}
          name: project_1
          # Required once per host
          known_hosts: ${{ secrets.SSH_KNOWN_HOSTS }}
      - name: GitHub SSH Authentication for Project 2
        uses: shimataro/ssh-key-action@v2
        with:
          key: ${{ secrets.SSH_PRIVATE_KEY_PROJECT_2 }}
          name: project_2
      - name: Prepare the Python environment
        shell: bash
        run: bash ${GITHUB_WORKSPACE}/.github/scripts/create_python_venv.sh

where in .github/scripts/create_python_venv.sh there is pip install -r requirements.txt command which contains the following:

# requirements.txt
git+ssh://[email protected]/myuser/project_1.git@develop#egg=project_1
git+ssh://[email protected]/myuser/project_2.git@develop#egg=project_2

As both URLs in requirements file require a different SSH key pair to work even though the host is the same.

Permission denied (publickey,gssapi-keyex,gssapi-with-mic)

    steps:
      - name: Install SSH key
        uses: shimataro/ssh-key-action@v1
        with:
          name: id_rsa-prod
          private-key: ${{ secrets.RSA_KEY }}
          known-hosts: ${{ secrets.SSH_KNOWN_HOSTS }}
          config: |
            Host prod
              HostName ${{ secrets.SERVER_IP }}
              Port ${{ secrets.SERVER_PORT }}
              User ${{ secrets.SERVER_USER }}

      - name: Publish
        run: |
          ssh prod -tt -i ~/.ssh/id_rsa-prod

output

Run ssh prod -tt -i ~/.ssh/id_rsa-prod
***@***: Permission denied (publickey,gssapi-keyex,gssapi-with-mic).
##[error]Process completed with exit code 255.

my sshd_config

PasswordAuthentication no
RSAAuthentication yes
PubkeyAuthentication yes

How can i do?

Key not installed but no error message thrown

Hi,

I'm running the action on a Linux Ubuntu 20.04.2 machine.
Runner version 2.276.1

The action log indicates that the key has been installed successfully, but it does not work. I have inspected the key installation path ~/.ssh, and all seems right (the files have been copied, etc.). So I continued trying to install the key manually using the files already there by running ssh-add id_rsa, and I got the error message Error loading key "id_rsa": invalid format. Examining the id_rsa file, I have discovered that the action adds a '\n' at the end of the key file that invalidates the key. After removing the line with nano and rerunning ssh-add id_rsa, everything works nicely. I also double-checked that the '\n' wasn't part of the original secret in GitHub. In my particular case, I assume the error is produced by the insertion of that trailing '\n' that invalidates the key.

Cheers,
Ramon

Getting error when using the latest version

Getting following error for the last 1 hour

Could not find file '/home/runner/work/_actions/_temp_16a41acc-ee83-42d0-8687-5ea6451234ef/_staging/shimataro-ssh-key-action-da773c8/node_modules/.bin/installed-package-contents'.

@shimataro Could you please look in to it, I think the last release is causing the issue.

node_modules/@actions/core is committed & node_modules isn't included in .gitignore

npm install installs a lot of files in node_modules, and they are tracked by Git. We may add them to new commits by mistake.
Actually, node_modules/@actions/core has already been committed. Is this intended?

🇯🇵
npm installnode_moduleに大量のファイルをインストールするため、Gitに追跡されてしまいます。これでは間違ってコミットしてしまいます。実際、node_modules/@actions/coreがコミットされてしまっています。これは意図的なものでしょうか?

python2 error

The error log in github actions is:

Build container for action use: '/home/runner/work/_actions/Borales/actions-yarn/v2.3.0/Dockerfile'.
  /usr/bin/docker build -t 5364e3:0b59324d8a3048e3a6d51729d29eb77c -f "/home/runner/work/_actions/Borales/actions-yarn/v2.3.0/Dockerfile" "/home/runner/work/_actions/Borales/actions-yarn/v2.3.0"
  Sending build context to Docker daemon  7.168kB
  
  Step 1/6 : FROM node:lts-alpine
  lts-alpine: Pulling from library/node
  213ec9aee27d: Already exists
  bb60732a8e9f: Pulling fs layer
  9f61bc6ef19c: Pulling fs layer
  8de0f21617f6: Pulling fs layer
  8de0f21617f6: Verifying Checksum
  8de0f21617f6: Download complete
  9f61bc6ef19c: Verifying Checksum
  9f61bc6ef19c: Download complete
  bb60732a8e9f: Verifying Checksum
  bb60732a8e9f: Download complete
  bb60732a8e9f: Pull complete
  9f61bc6ef19c: Pull complete
  8de0f21617f6: Pull complete
  Digest: sha256:7584b116f368d94fab2ecc21ebbcfd5434a3427c2f96f846972821b5ad0266fc
  Status: Downloaded newer image for node:lts-alpine
   ---> f7ef5856dc1f
  Step 2/6 : RUN apk add --no-cache git python2 build-base
   ---> Running in b2de8a6d0639
  fetch https://dl-cdn.alpinelinux.org/alpine/v3.16/main/x86_64/APKINDEX.tar.gz
  fetch https://dl-cdn.alpinelinux.org/alpine/v3.16/community/x86_64/APKINDEX.tar.gz
  ERROR: unable to select packages:
    python2 (no such package):
      required by: world[python2]
  The command '/bin/sh -c apk add --no-cache git python2 build-base' returned a non-zero code: 1
  Warning: Docker build failed with exit code 1, back off 6.[47](https://github.com/endless-mirage/xx-shop-admin/actions/runs/3202280208/jobs/5231106161#step:2:47)7 seconds before retry.

The gitaction.yml:

  build-deploy:
    runs-on: ubuntu-latest
    concurrency: production
    steps:
    - name: Install ssh key
      uses: shimataro/[email protected]
      with:
        key: ${{ secrets.SSH_GITHUB_ACTION }}
        known_hosts: 'just-a-placeholder-so-we-dont-get-errors'

How can I fix this?

Make known_hosts optional

Our use case is pretty simple - add a GitHub SSH key so we can push to GitHub without using a token. GitHub known_hosts ssh key is already added by default, so we don't need to add one ourselves.

Would be nice to make this field optional.

Rsync fails Permission denied (publickey)

Install SSH Key working

Run shimataro/ssh-key-action@v[2](https://github.com/gamerplex/kinland2/actions/runs/4005511431/jobs/6876611514#step:3:2)
  with:
    key: ***
  
    name: id_rsa
    known_hosts: just-a-placeholder-so-we-dont-get-errors
    if_key_exists: replace
SSH key has been stored to /home/runner/.ssh successfully.

But when running rsync command, it fails

Run rsync -avzr ./build/WebGL/* root@***:/home/steve777/apps/***-Web/                 
  rsync -avzr ./build/WebGL/* root@***:/home/steve777/apps/***-Web/                 
  shell: /usr/bin/bash -e {0}
root@***: Permission denied (publickey).
rsync: connection unexpectedly closed (0 bytes received so far) [sender]
rsync error: unexplained error (code [2]
Error: Process completed with exit code 2[5]

I am also using appleboy/ssh-action with same host and private_key but that works fine.

Run appleboy/[email protected]
  with:
    host: ***
    username: root
    key: ***
    port: 22
    script: cd /home/steve777/apps/***-Web
  rm -rf *
  
    sync: false
    use_insecure_cipher: false
    timeout: 0s
    command_timeout: 10m
    proxy_port: 22
    proxy_timeout: 30s
    proxy_use_insecure_cipher: false
    script_stop: false
    debug: false

======CMD======
cd /home/steve[7](https://github.com/gamerplex/kinland2/actions/runs/4005511431/jobs/6876611514#step:7:7)77/apps/Kinland-Web
rm -rf *

======END======
==============================================
✅ Successfully executed commands to all host.
==============================================

Workflow

deployToWebServer:
    needs: [BuildWebGL]
    #runs-on: self-hosted
    runs-on: ubuntu-latest
    steps:
      - name: Install SSH Key
        uses: shimataro/ssh-key-action@v2
        with:
          key: ${{ secrets.SSH_PRIVATE_KEY }} 
          name: id_rsa
          known_hosts: 'just-a-placeholder-so-we-dont-get-errors'
          if_key_exists: replace
          
      - name: Adding Known Hosts
        run: ssh-keyscan -H ${{ secrets.SSH_HOST_WEBGL }} >> ~/.ssh/known_hosts
      
  
        #Checkout
      - uses: actions/checkout@v3
        with:
            #fetch-depth: 0
            #Branch
            ref: main
            fetch-depth: 1
            submodules: recursive
            #token:  ${{ secrets.MY_PAT }}
 
        #Repeat for all builds, copy paste this step
      - name: Download WebGL Artifact
        uses: actions/download-artifact@v2
        with:
          name: Build-WebGL
          path: build/WebGL
      
      - name: Cleanup Remote Old Files
        uses: appleboy/[email protected]
        with:
            host: ${{ secrets.SSH_HOST_WEBGL }}
            username: root
            key: ${{ secrets.SSH_PRIVATE_KEY_WEBGL }} 
            port: 22
            script: |
              cd /home/steve777/apps/***-Web
              rm -rf *
      
      - name: Deploy with rsync
        run: |
            rsync -avzr ./build/WebGL/* root@${{ secrets.SSH_HOST_WEBGL }}:/home/steve777/apps/***-Web/    

Error: HOME is not defined

I start my hosted runner and when it gets to the ssh-key-action step, I get the error message in the subject.
When I ssh into the runner and executes:
echo $HOME, I get /home/ubuntu as expected

What am I missing here?

Host key verification failed

Hi guys, I tried to run sh script using your action but couldn't. Can you help me find what I did wrong?
Here is the key and host I added and my yml file. Thank you!
Screenshot 2020-10-30 at 17 58 41
Screenshot 2020-11-01 at 14 45 22
Screenshot 2020-11-01 at 11 54 01
Screenshot 2020-11-01 at 11 55 25

Permission denied (publickey) for git clone

First of all, thank you for great job by developing this GitHub action.

I am trying to access multiple private repositories from GitHub Actions, which are linked to my main project as dependencies(SPM).

I successfully fetch SSH keys for both private repos. However, when I try to git clone them, output shows the following message:

[email protected]: Permission denied (publickey).
[8](https://github.com/eazel/iOSNetwork/runs/6806557664?check_suite_focus=true#step:7:9)
fatal: Could not read from remote repository.
[9](https://github.com/eazel/iOSNetwork/runs/6806557664?check_suite_focus=true#step:7:10)
[10](https://github.com/eazel/iOSNetwork/runs/6806557664?check_suite_focus=true#step:7:11)
Please make sure you have the correct access rights
[11](https://github.com/eazel/iOSNetwork/runs/6806557664?check_suite_focus=true#step:7:12)
and the repository exists.
[12](https://github.com/eazel/iOSNetwork/runs/6806557664?check_suite_focus=true#step:7:13)
Error: Process completed with exit code 128.

Here is my workflow:

- name: Install SSH key for first kit
      uses: shimataro/ssh-key-action@v2
      with:
        key: ${{ secrets.SSH_KEY_FIRST }}
        name: id_rsa-first
        known_hosts: unnecessary
    
    - name: Install SSH key for second kit
      uses: shimataro/ssh-key-action@v2
      with:
        key: ${{ secrets.SSH_KEY_SECOND }}
        name: id_rsa-second
        known_hosts: unnecessary
        
    - name: print created files
      run: ls -l ~/.ssh
    
    - name: git clone first
      run: git clone [email protected]:link
      
    - name: git clone second
      run: get clone [email protected]:link

Host key verification failed

Hi, i have this successfully adding the ssh keys, but when i attempt to test with a following step, i receive Host key verification failed.
Before this command, i run ls -a on the .ssh folder and i do see the files... any thoughts?

relevant code:

        uses: shimataro/ssh-key-action@v1
        with:
          private-key: ${{ secrets.SSH_PRIVATE_KEY }}
          public-key: ${{ secrets.SSH_PUBLIC_KEY }}
          name: wpengine_rsa # optional
          # known-hosts: ${{ secrets.KNOWN_HOSTS }} # known_hosts; optional
      # config: ${{ secrets.CONFIG }} # ssh_config; optional
      - name: git test
        run: |
          cd /home/runner/.ssh
          ls -a
          ssh [email protected] info 

Host key verification failed.

Hey all,

I have this problem as others.

Run if [ "refs/heads/4-implement-workflows" = "refs/heads/main" ]; then
  if [ "refs/heads/4-implement-workflows" = "refs/heads/main" ]; then
    rsync -avz dist/ ***@***:***
  else
    rsync -avz dist/ ***@***:***
  fi
  shell: /usr/bin/bash -e {0}
Host key verification failed.
rsync: connection unexpectedly closed (0 bytes received so far) [sender]
rsync error: unexplained error (code 255) at io.c(231) [sender=3.2.7]
Error: Process completed with exit code 255.

This is my workflow config

deploy:
    needs: build
    runs-on: ubuntu-latest
    steps:
      - name: Checkout code
        uses: actions/checkout@v2
      - name: Install SSH Key
        uses: shimataro/ssh-key-action@v2
        with:
          name: github_rsa
          key: ${{ secrets.SSH_PRIVATE_KEY }}
          known_hosts: ${{ secrets.SSH_KNOWN_HOSTS }}
          config: |
            Host ${{ secrets.SSH_HOST }}
              HostName ${{ secrets.SSH_HOST }}
              User ${{ secrets.SSH_USER }}
              IdentityFile ~/.ssh/github_rsa
              Port ${{ secrets.SSH_PORT }}
      - name: Deploy to VPS
        run: |
          if [ "${{ github.ref }}" = "refs/heads/main" ]; then
            rsync -avz dist/ ${{ secrets.SSH_USER }}@${{ secrets.SSH_HOST }}:${{ secrets.SSH_PRODUCTION_PATH }}
          else
            rsync -avz dist/ ${{ secrets.SSH_USER }}@${{ secrets.SSH_HOST }}:${{ secrets.SSH_STAGING_PATH }}
          fi

My secrets list in github

Screenshot 2024-03-16 at 11 39 09

Considerations:

  • I generated the SSH_KNOWN_HOSTS with the command ssh-keyscan -p PORT IP_ADDRESS against my remote host.
  • SSH_PRIVATE_KEY is obviously the private key installed on the remote host (IdentityFile in config).

Am I missing something?

Feature Request: strip cr/lf endings from ssh key

I'm running this action on Gitea, and today I have discovered Gitea saves secrets with cr/lf Windows style endings, which makes git clone fail, even though I run Gitea via Docker, and none of my computers have Windows:

Load key "/root/.ssh/id_rsa": invalid format
[email protected]: Permission denied (publickey).
fatal: Could not read from remote repository.

I had to add this extra step to fix the issue:

- name: Fix SSH key
  run: sed -i 's/\r$//g' /root/.ssh/id_rsa

I do realize this issue is on Gitea side, which I will report, but would appreciate if you could implement same functionality but within this action and add one extra config option, for such scenarios. Like:

- name: Install SSH Key
  uses: shimataro/[email protected]
  with:
    key: ${{ secrets.SSH_KEY }}
    key_strip_cr: true
    known_hosts: ${{ secrets.SSH_KNOWN_HOSTS }}
    config: |
      Host git.example.com
        Port 12345
        User git

Thanks!

"known_hosts" option

StrictHostKeyChecking=no option is not secure.
.ssh/known_hosts is required for security.

example:

- name: Install SSH key
  uses: shimataro/ssh-key-action@v1
  with:
    private-key: ${{ secrets.SSH_KEY }}
    public-key: ${{ secrets.SSH_KEY_PUBLIC }}
    name: id_rsa # optional
    known-hosts: ${{ secrets.KNOWN_HOSTS }} # optional

GitHub Actions CI triggered by PRs by others fails

Encrypted secrets in GitHub Actions are not passed to builds triggered by forked repositories (PRs from others).
https://docs.github.com/ja/free-pro-team@latest/actions/reference/encrypted-secrets#%E6%9A%97%E5%8F%B7%E5%8C%96%E3%81%95%E3%82%8C%E3%81%9F%E3%82%B7%E3%83%BC%E3%82%AF%E3%83%AC%E3%83%83%E3%83%88%E3%81%AE%E3%83%AF%E3%83%BC%E3%82%AF%E3%83%95%E3%83%AD%E3%83%BC%E5%86%85%E3%81%A7%E3%81%AE%E5%88%A9%E7%94%A8 (Japanese)
This makes Connect to github.com and Connect to github.com with name and config for PRs fail.

Take /.github/workflows/verify-on-ubuntu-2004.yml as an example.

name: Connect to github.com
runs-on: ubuntu-20.04
steps:
- name: Checkout source codes
uses: actions/checkout@v2
- name: Install SSH key
uses: ./.
with:
key: ${{ secrets.SSH_KEY }}
known_hosts: ${{ secrets.KNOWN_HOSTS }}

In this configuration, key and known_hosts are ignored in PRs (except for yours). Options passed to builds for my PR are:

Run ./.
  with:
    name: id_rsa
Error: Input required and not supplied: key

name: id_rsa is the default option, so you can see those 2 options are missing.

It may be fixed by changing the SSH target to one created by Docker (you do not have to apply it to builds for develop branch).


Image candidate: https://github.com/linuxserver/docker-openssh-server

Error on run `ssh-keyscan`

When run ssh-keyscan -p ${{ inputs.ssh-port }} -H ${{ inputs.ssh-host }} > ~/.ssh/known_hosts pipeline brakes with message Process completed with exit code 1.

This pipeline works normally until October 2022 and now I have used it again and it does not generate known_hosts I have tried to generate it directly but also without success.

Action

name: Test, build and deploy
inputs:
  ssh-user:
    required: true
  ssh-host:
    required: true
  ssh-port:
    default: '22'
    required: true
  ssh-key:
    required: true
runs:
  using: 'composite'
  steps:
    - name: Install SSH Key
      uses: shimataro/ssh-key-action@v2
      with:
        key: ${{ inputs.ssh-key }}
        known_hosts: 'unnecessary'
    - name: Adding Known Hosts
      run: |
        ls -la ~/.ssh
        ssh-keyscan -p ${{ inputs.ssh-port }} -H ${{ inputs.ssh-host }} > ~/.ssh/known_hosts
      shell: bash

**Error log

2023-09-25T21:25:42.0281881Z ##[group]Run shimataro/ssh-key-action@v2
2023-09-25T21:25:42.0282382Z with:
2023-09-25T21:25:42.0288492Z   key: ***
2023-09-25T21:25:42.0288928Z   known_hosts: unnecessary
2023-09-25T21:25:42.0289357Z   name: id_rsa
2023-09-25T21:25:42.0289780Z   if_key_exists: fail
2023-09-25T21:25:42.0290174Z env:
...
2023-09-25T21:25:42.0294471Z ##[endgroup]
2023-09-25T21:25:42.1863846Z SSH key has been stored to /home/runner/.ssh successfully.
2023-09-25T21:25:42.2061313Z ##[group]Run ls -la ~/.ssh
2023-09-25T21:25:42.2061836Z �[36;1mls -la ~/.ssh�[0m
2023-09-25T21:25:42.2062533Z �[36;1mssh-keyscan -p *** -H *** > ~/.ssh/known_hosts�[0m
2023-09-25T21:25:42.2128952Z shell: /usr/bin/bash --noprofile --norc -e -o pipefail {0}
2023-09-25T21:25:42.2129495Z env:
...
2023-09-25T21:25:42.2133742Z ##[endgroup]
2023-09-25T21:25:42.2328283Z total 16
2023-09-25T21:25:42.2329547Z drwx------  2 runner docker 4096 Sep 25 21:25 .
2023-09-25T21:25:42.2330726Z drwxr-x--- 16 runner docker 4096 Sep 25 21:25 ..
2023-09-25T21:25:42.2331642Z -r--------  1 runner docker 1679 Sep 25 21:25 id_rsa
2023-09-25T21:25:42.2332510Z -rw-r--r--  1 runner docker  565 Sep 25 21:25 known_hosts
2023-09-25T21:25:47.2710086Z ##[error]Process completed with exit code 1.

Does anyone have any suggestions?

Cannot connect to SSH via Github action

I use the following yml file to deploy my website code via SSH but I meet the error below:

on:
  push:
    branches:
      - main
  workflow_dispatch:
jobs:

  build:
    name: Build Website
    runs-on: ubuntu-latest

    steps:
      - name: Checkout Repository
        uses: actions/checkout@v2

      - name: Install Dependencies
        run: yarn install --frozen-lockfile
      - name: Build SSR
        run: npx quasar build -m ssr

      - name: Upload Build Artifacts
        uses: actions/upload-artifact@v2
        with:
          name: build-artifacts
          path: './dist/ssr'

  deploy:
    name: Deploy to Production
    runs-on: ubuntu-latest
    needs: [build]
   
    steps:
      - name: Install SSH Key
        uses: shimataro/ssh-key-action@v2
        with:
          key: ${{ secrets.SSH_KEY }}
          known_hosts: 'just-a-placeholder-so-we-dont-get-errors'

      - name: Adding Known Hosts
        run: ssh-keyscan -p ${{ secrets.SSH_PORT }} -H ${{ secrets.SSH_HOST }} >> ~/.ssh/known_hosts

      - name: Deploy with rsync
        # run: rsync -avz -e "ssh -p ${{ secrets.SSH_PORT }}" ./dist/ssr ${{ secrets.SSH_USER }}@${{ secrets.SSH_HOST }}:${{ vars.HOST_PATH }}
        run: rsync -avz -e "ssh -oHostKeyAlgorithms=+ssh-rsa -p ${{ secrets.SSH_PORT }}" ./dist/ssr/ ${{ secrets.SSH_USER }}@${{ secrets.SSH_HOST }}:${{ vars.HOST_PATH }}

Error:

##[debug]Evaluating condition for step: 'Deploy with rsync'
##[debug]Evaluating: success()
##[debug]Evaluating success:
##[debug]=> true
##[debug]Result: true
##[debug]Starting: Deploy with rsync
##[debug]Loading inputs
##[debug]Evaluating: format('rsync -avz -e "ssh -oHostKeyAlgorithms=+ssh-rsa -p {0}" ./dist/ssr/ {1}@{2}:{3}', secrets.SSH_PORT, secrets.SSH_USER, secrets.SSH_HOST, vars.HOST_PATH)
##[debug]Evaluating format:
##[debug]..Evaluating String:
##[debug]..=> 'rsync -avz -e "ssh -oHostKeyAlgorithms=+ssh-rsa -p {0}" ./dist/ssr/ {1}@{2}:{3}'
##[debug]..Evaluating Index:
##[debug]....Evaluating secrets:
##[debug]....=> Object
##[debug]....Evaluating String:
##[debug]....=> 'SSH_PORT'
##[debug]..=> '***'
##[debug]..Evaluating Index:
##[debug]....Evaluating secrets:
##[debug]....=> Object
##[debug]....Evaluating String:
##[debug]....=> 'SSH_USER'
##[debug]..=> '***'
##[debug]..Evaluating Index:
##[debug]....Evaluating secrets:
##[debug]....=> Object
##[debug]....Evaluating String:
##[debug]....=> 'SSH_HOST'
##[debug]..=> '***'
##[debug]..Evaluating Index:
##[debug]....Evaluating vars:
##[debug]....=> Object
##[debug]....Evaluating String:
##[debug]....=> 'HOST_PATH'
##[debug]..=> '/home/***/ssr/'
##[debug]=> 'rsync -avz -e "ssh -oHostKeyAlgorithms=+ssh-rsa -p ***" ./dist/ssr/ ***@***:/home/***/ssr/'
##[debug]Result: 'rsync -avz -e "ssh -oHostKeyAlgorithms=+ssh-rsa -p ***" ./dist/ssr/ ***@***:/home/***/ssr/'
##[debug]Loading env
Run rsync -avz -e "ssh -oHostKeyAlgorithms=+ssh-rsa -p ***" ./dist/ssr/ ***@***:/home/***/ssr/
##[debug]/usr/bin/bash -e /home/runner/work/_temp/34c64e52-8d53-407f-9c49-c1e6fd415600.sh
sign_and_send_pubkey: no mutual signature supported
Permission denied, please try again.
Permission denied, please try again.
***@***: Permission denied (publickey,password).
rsync: connection unexpectedly closed (0 bytes received so far) [sender]
rsync error: error in rsync protocol data stream (code 12) at io.c(231) [sender=3.2.7]
Error: Process completed with exit code 12.
##[debug]Finishing: Deploy with rsync

FYI I'm able to connect via ssh using other machine!

I expect to connect without problem!

Syntax for known_hosts

I couldn't find documentation on the syntax used by known_hosts. What should the syntax be?

For the host I want to connect to, I have the following information (from WinSCP):

image

How should I code this into the known_hosts field?

Also, it says hosts, plural? Shouldn't it be just one host, the one I am trying to connect to?

OpenSSH claims private keys are illegal because LF after the last line of them are removed

      - name: Install SSH Key (target)
        uses: shimataro/[email protected]
        with:
          # SSH private key
          key: |+
            ${{ secrets.DEPLOY_SSH_KEY }}
          name: id_target
          known_hosts: ${{ secrets.DEPLOY_HOST_KEY }}
          # SSH config
          config: |
            Host target
            HostName ${{ secrets.DEPLOY_HOST }}
            User ${{ secrets.DEPLOY_HOST_USER }}
            Port ${{ secrets.DEPLOY_HOST_PORT }}
            IdentityFile ~/.ssh/id_target
            ProxyJump jumphost
      - name: Complete EOL in EOF of SSH keys
        run: |
          for key in ~/.ssh/id_target; do
            chmod +w $key
            [[ `tail -c 1 $key` != `echo` ]] && echo >> $key
            chmod -w $key
          done
        shell: bash

I couldn't install an OpenSSH private key only with the 1st step.
I managed to do it by adding the 2nd step.
It makes up for the lost LF in the last line. (----- -> -----\n)
tail -c 1 $key outputs - if the last LF is missing, or \n (equals to the output of echo) if alive.

Remove only specific ssh key after execution

Follow up to #199:

Thanks so much for the update #224. That will be very useful for some use cases.

I was wondering if removing the .ssh folder is a reliable cleanup process? What if IT has a few SSH keys preinstalled on that server? We don't want to delete them unless they were added by the action during this run.

Stored key not picked up by scp

Hello!

First, thanks for this action, really nice!

I have the problem, that the saved key file is not found by a call to scp in the following step.

This is how I call your action:

    - name: Install SSH key
      uses: shimataro/ssh-key-action@v1
      with:
        private-key: ${{ secrets.SSH_KEY_PRODUCTION }}
        public-key: ${{ secrets.SSH_KEY_PRODUCTION_PUBLIC }}

In the log of my workflow I see the following message (so I assume everything worked as expected):

Run shimataro/ssh-key-action@v1
  with:
    private-key: ***
    public-key: ***
    name: id_rsa
SSH key has been stored to /home/runner/.ssh successfully.

In my workflow then I call scp like this:

- name: Deploy to production
      if: github.ref == 'refs/heads/master'
      run: |
        scp -v ./docker-compose.yml [email protected]:/somedir/

In the log of my workflow I see that the file is not found:

Run scp -v ./docker-compose.yml [email protected]:/codefrog/
Executing: program /usr/bin/ssh host 142.93.196.203, user codefrog, command scp -v -t /codefrog/
OpenSSH_7.6p1 Ubuntu-4ubuntu0.3, OpenSSL 1.0.2n  7 Dec 2017
debug1: Reading configuration data /etc/ssh/ssh_config
debug1: /etc/ssh/ssh_config line 19: Applying options for *
debug1: Connecting to 142.93.196.203 [142.93.196.203] port 22.
debug1: Connection established.
debug1: identity file /home/runner/.ssh/id_rsa type 0   <--- *** HERE! ***
debug1: key_load_public: No such file or directory
debug1: identity file /home/runner/.ssh/id_rsa-cert type -1
debug1: key_load_public: No such file or directory
debug1: identity file /home/runner/.ssh/id_dsa type -1
debug1: key_load_public: No such file or directory
debug1: identity file /home/runner/.ssh/id_dsa-cert type -1
debug1: key_load_public: No such file or directory
debug1: identity file /home/runner/.ssh/id_ecdsa type -1
debug1: key_load_public: No such file or directory
debug1: identity file /home/runner/.ssh/id_ecdsa-cert type -1
debug1: key_load_public: No such file or directory
debug1: identity file /home/runner/.ssh/id_ed25519 type -1
debug1: key_load_public: No such file or directory
debug1: identity file /home/runner/.ssh/id_ed25519-cert type -1
debug1: Local version string SSH-2.0-OpenSSH_7.6p1 Ubuntu-4ubuntu0.3
debug1: Remote protocol version 2.0, remote software version OpenSSH_7.6p1 Ubuntu-4ubuntu0.3

Can you please help me. What am I missing?
Thank you very much!

Run ssh-key-action on Private container

First of all, thanks for the repo. It worked for me using a runs-on: ubuntu-latest but I have tested it with github actions using a private docker image and seems that it was not getting the right behaviour.
Using the action as follows in a private docker image as follows:

runs-on: ubuntu-latest
    container:
      image: gcr.io/api/image:latest
      credentials:
        username: _json_key
        password: ${{secrets.password}}
steps:
- name: Install SSH key
      uses: shimataro/ssh-key-action@v2
      with:
        key: ${{ secrets.KEY }}
        name: id_rsa
        known_hosts: github.com

Wasn't getting access to the repositories I needed, and I found that known_hosts file was not well formatted and the ssh path was /github/home/.ssh instead of /root/.ssh, as it seems the image needed.
To solve that, this commands made the trick:

ssh-keyscan github.com > /github/home/.ssh/known_hosts
cp -avr /github/home/.ssh /root/.ssh

panic: ssh tcp to server: ssh: handshake failed: ssh: unable to authenticate, attempted methods [none publickey], no supported methods remain

I've done all these steps:

  1. Created a new SSH key
  2. Added it to the target server
  3. Restarted the SSH service on the target server
  4. Connected with the new SSH key from my Mac to the target server (Worked)
  5. Added the SSH key to the CI/CD runner manually (Self hosted)
  6. Connected from the CI/CD runner to the target server (worked)
  7. Copied the SSH key to github secrets
  8. Copied the KNOWN_HOSTS to github secrets
  9. Run the github action
  10. Got this error: panic: ssh tcp to server: ssh: handshake failed: ssh: unable to authenticate, attempted methods [none publickey], no supported methods remain

ssh-key-action step failing with GLIBC not found error

Hi, my current GitHub action is failing at the ssh-key-action step running the the action with the following error. I think it is caused by node version 20.

/home//actions-runner/externals/node20/bin/node: /lib64/libm.so.6: version GLIBC_2.27' not found (required by /home/***/actions-runner/externals/node20/bin/node) /home/***/actions-runner/externals/node20/bin/node: /lib64/libstdc++.so.6: version GLIBCXX_3.4.20' not found (required by /home//actions-runner/externals/node20/bin/node)
/home//actions-runner/externals/node20/bin/node: /lib64/libstdc++.so.6: version CXXABI_1.3.9' not found (required by /home/***/actions-runner/externals/node20/bin/node) /home/***/actions-runner/externals/node20/bin/node: /lib64/libstdc++.so.6: version GLIBCXX_3.4.21' not found (required by /home//actions-runner/externals/node20/bin/node)
/home//actions-runner/externals/node20/bin/node: /lib64/libc.so.6: version GLIBC_2.2[8](https://github.com/uic-ts/SDD-mysqlportal-nodepug-serverclient/actions/runs/7889127784/job/21528315412#step:6:9)' not found (required by /home/***/actions-runner/externals/node[2](https://github.com/uic-ts/SDD-mysqlportal-nodepug-serverclient/actions/runs/7889127784/job/21528315412#step:17:2)0/bin/node) /home/***/actions-runner/externals/node20/bin/node: /lib6[4](https://github.com/uic-ts/SDD-mysqlportal-nodepug-serverclient/actions/runs/7889127784/job/21528315412#step:17:4)/libc.so.6: version GLIBC_2.25' not found (required by /home//actions-runner/externals/node20/bin/node)

Error loading key "/home/runner/.ssh/deploy_key": invalid format while format is RSA

My key is just an RSA key and i've added it to the SECRETS in github. This is my setup:

- name: Setup SSH key
        uses: shimataro/ssh-key-action@v2
        with:
          key: ${{ env.SSH_KEY }}
          name: deploy_key # optional
          known_hosts: unnecessary
          if_key_exists: ignore # replace / ignore / fail; optional (defaults to fail)
- name: Deploy to server
        run: |
          eval `ssh-agent -s`
          ssh-add ~/.ssh/deploy_key
          rsync -avz ./backend/dist/ root@$SSH_HOST:/serve/backend/
          rsync -avz ./frontend/.next/ root@$SSH_HOST:/serve/frontend/

Public key

Would you consider an additional input so you would write .pub as well?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.