使用nektos/act本地测试GitHub Actions时gh命令未找到的解决方法
问题:本地用nektos/act测试GitHub Actions时gh命令找不到
我用nektos/act在本地测试GitHub Actions,原本用curl请求的YAML脚本能正常运行:
pull_info=$(curl -L -w "%{http_code}" -H "Accept: application/vnd.github+json" -H "Authorization: Bearer ${{ secrets.GITHUB_TOKEN }}" -H "X-GitHub-Api-Version: 2022-11-28" https://api.github.com/repos/${{ github.repository }}/pulls/${{ github.event.pull_request.number }})
但把curl替换为GitHub CLI命令后:
pull_info=$(gh pr view ${{ github.event.pull_request.number }} --repo ${{ github.repository }} --json title,number,state)
测试时act报错:
/var/run/act/workflow/0: line 4: gh: command not found
我试过执行gh extension install nektos/gh-act安装扩展,但问题仍未解决,求修复方法或其他测试方式。
修复方法
1. 在Workflow步骤中预先安装GitHub CLI
act默认使用的Docker镜像未预装gh命令,需要在运行gh命令的步骤前,先添加安装gh的步骤:
- name: Install GitHub CLI run: | type -p curl >/dev/null || sudo apt install curl -y curl -fsSL https://cli.github.com/packages/githubcli-archive-keyring.gpg | sudo dd of=/usr/share/keyrings/githubcli-archive-keyring.gpg \ && sudo chmod go+r /usr/share/keyrings/githubcli-archive-keyring.gpg \ && echo "deb [arch=$(dpkg --print-architecture) signed-by=/usr/share/keyrings/githubcli-archive-keyring.gpg] https://cli.github.com/packages stable main" | sudo tee /etc/apt/sources.list.d/github-cli.list > /dev/null \ && sudo apt update \ && sudo apt install gh -y
安装完成后,再执行包含gh命令的步骤即可。
2. 使用预装有gh的自定义Docker镜像
选择一个已经包含GitHub CLI的镜像(比如官方的alpine/gh),运行act时指定该镜像:
act -i alpine/gh:latest
也可以在项目根目录的.actrc配置文件中添加默认镜像设置:
-i alpine/gh:latest
3. 挂载本地已安装的gh到容器
如果你的本地机器已经安装了GitHub CLI,可以将其挂载到act的运行容器中,避免重复安装:
act -v $(which gh):/usr/local/bin/gh
$(which gh)会自动获取本地gh的安装路径,确保容器内可以直接调用。
其他测试方式
- 本地直接调试gh命令:跳过act,直接在本地终端运行gh命令验证逻辑,例如:
gh pr view <PR_NUMBER> --repo <OWNER/REPO> --json title,number,state
- 使用GitHub官方本地 runner:GitHub提供了官方的本地Actions运行工具,不过act仍是社区最常用的本地测试工具,优先解决gh安装问题更高效。
内容的提问来源于stack exchange,提问作者Артем Лебідь
相关产品推荐
相关产品推荐

