使用PyGithub无法获取GitHub仓库Secrets值的解决方法咨询
问题解答:无法通过PyGithub获取GitHub仓库Secrets的解决方案
核心原因
GitHub仓库的Secrets是敏感数据,出于安全设计,不允许通过外部API直接读取明文值——哪怕你用拥有仓库权限的个人AccessToken(ghp_开头的令牌)调用API,也只能获取Secrets的元数据(比如名称、创建时间),无法拿到实际的value。而Variables是公开的配置项,所以可以直接读取。
可行的解决方案/替代方案
1. 利用GitHub Actions导出Secrets
如果只是需要手动获取Secrets的值,可以通过GitHub Actions工作流将Secrets导出为文件并上传为Artifact:
name: 导出Secret到Artifact on: workflow_dispatch # 支持手动触发 jobs: export-secret: runs-on: ubuntu-latest steps: - name: 将Secret写入文件 run: echo "${{ secrets.DEMO_TOKEN }}" > secret.txt - name: 上传为Artifact uses: actions/upload-artifact@v4 with: name: secret-file path: secret.txt
- 操作步骤:在仓库的Actions页面找到这个工作流,点击"Run workflow"触发,执行完成后在工作流详情里下载Artifact,就能拿到Secrets的值。
- 注意:只有拥有仓库写入权限的用户才能触发这个工作流并下载Artifact,确保操作环境安全。
2. 在GitHub托管环境内使用Secrets(自动化场景)
如果是自动化脚本需要使用Secrets,不要在外部环境调用API读取,而是将脚本放在GitHub Actions、Codespaces或者GitHub App的运行环境中:
- 在GitHub Actions里直接通过
${{ secrets.DEMO_TOKEN }}引用Secrets; - 如果用GitHub App,给App分配仓库的
Secrets (read)权限,然后在GitHub内部环境中通过App身份调用API使用Secrets(依然无法拿到明文,但可以在环境中直接使用)。
3. 改用仓库Variables存储非敏感数据
如果你的数据不需要严格保密,直接将其存入仓库Variables,就可以用你当前的代码直接读取:
from github import Github github_token = 'ghp_xxx' github = Github(github_token) repo = github.get_repo('bhupender/repo_name') variable = repo.get_variable("DEMO_TOKEN") print(variable.value)
关于PyGithub调用Secrets的说明
PyGithub中确实有get_secret方法,但调用后只能获取Secrets的元数据,无法拿到明文值:
from github import Github github_token = 'ghp_xxx' github = Github(github_token) repo = github.get_repo('bhupender/repo_name') secret = repo.get_secret("DEMO_TOKEN") print(secret.name) # 可以正常返回Secret名称 print(secret.created_at) # 可以返回创建时间 print(secret.value) # 会返回None,因为GitHub API不返回明文值
内容的提问来源于stack exchange,提问作者Bhupender
相关产品推荐
相关产品推荐

