需求
push 某个分支后把该分支的内容自动部署到远程服务器上。
分析
首先需要创建一个 Github Actions,这个在仓库的 actions 选项里。可以直接创建一个最简单的 Action,搜 git 即可。创建 action 后编辑 .yml 文件,我们的目的是在 push 事件后自动连接到远程服务器并执行 git pull 指令。基本模板如下:
# action 名
name: ssh
on:
push:
# 在如下分支的 push 事件触发时,执行 jobs
branches: [ "master" ]
# 开启可以手动执行 action,不想开启可以删掉下面这行
workflow_dispatch:
jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
# 运行指令
- name: ssh login
run: echo "connect to remote terminal..."
配置 secrets
在连接到远程服务器之前需要配置服务器的端口、IP、用户名、密码、私钥等选项,很显然这些选项是不能写到代码文件里的。github 提供了 secrets 这个选项,作用类似环境变量,具体如何配置见:https://docs.github.com/en/actions/security-guides/encrypted-secrets
使用 run-ssh-command action
其实 Github 已经有现成的 ssh 连接轮子了,https://github.com/marketplace/actions/run-ssh-command
使用这个轮子后我们的 yml 文件如下:
# This is a basic workflow to help you get started with Actions
name: ssh
# Controls when the workflow will run
on:
# Triggers the workflow on push or pull request events but only for the "master" branch
push:
branches: [ "master" ]
pull_request:
branches: [ "master" ]
# Allows you to run this workflow manually from the Actions tab
workflow_dispatch:
# A workflow run is made up of one or more jobs that can run sequentially or in parallel
jobs:
# This workflow contains a single job called "build"
build:
# The type of runner that the job will run on
runs-on: ubuntu-latest
# Steps represent a sequence of tasks that will be executed as part of the job
steps:
# Checks-out your repository under $GITHUB_WORKSPACE, so your job can access it
- uses: actions/checkout@v3
- name: ls -a via ssh
uses: garygrossgarten/github-action-ssh@release
with:
command: ls -a
host: ${{ secrets.HOST }}
username: root
port: 9969
privateKey: ${{ secrets.PRIVATE_KEY}}
具体的 secrets 配置可以看上面的链接。
使用 ssh config
一般 ssh 的用法是命令行式,即 ssh username@ip -p port
这样的。今天查相关资料的时候发现还可以通过配置文件使用 ssh,文档:https://linux.die.net/man/5/ssh_config,使用配置文件的连接方法长这样:ssh hostname [command]
,其中 hostname 是我们在配置文件中定义的。ssh 连接(注意不是 sshd)的配置写在如下文件中:
~/.ssh/config
/etc/ssh/ssh_config
常用配置格式如下
# 使用 ssh hostname 连接时,hostname 的值
HOST Alice
# 服务器的IP或者域名
HostName 1.1.1.1
# 登录的用户名
User guest
# 私钥文件的目录
IdentityFile ~/.ssh/id_rsa
# 登录端口号,默认为 22
PORT 22
# 连接的时候是否询问用户把 host key 添加到 authorized_keys 中
# no 表示总是自动添加
# yes 总是询问用户是否添加
# ask 已被添加过的自动添加,否则询问
StrictHostKeyChecking no
那么连接方式就是 ssh Alice
。
而如何在 Github Action 中配置 ssh config,可以看这篇文章:https://blog.benoitblanchon.fr/github-action-run-ssh-commands/
总的思路就是创建 config 文件,然后连接的时候使用。