如何创建含密钥的多作业GitHub Actions工作流并解决凭证错误
多作业GitHub Actions工作流实现方案及凭证错误修复
以下是满足你需求的多作业工作流配置,同时解决pytest的凭证找不到问题:
name: Dev Branch CI/CD on: push: branches: [ dev ] pull_request: branches: [ dev ] jobs: # Python代码Lint作业 pylint: runs-on: ubuntu-latest steps: - name: Checkout code uses: actions/checkout@v4 - name: Set up Python uses: actions/setup-python@v5 with: python-version: '3.10' # 替换为你的Python版本 - name: Install dependencies run: | python -m pip install --upgrade pip pip install pylint pip install -r requirements.txt # 确保你的依赖文件正确 - name: Run pylint run: pylint src/ # 替换为你的代码目录 # Python测试作业 pytest: runs-on: ubuntu-latest steps: - name: Checkout code uses: actions/checkout@v4 - name: Set up Python uses: actions/setup-python@v5 with: python-version: '3.10' - name: Install dependencies run: | python -m pip install --upgrade pip pip install pytest google-auth # 确保安装所需依赖 pip install -r requirements.txt - name: Prepare Google credentials run: | # 将仓库密钥中的Google凭证JSON写入SDK默认读取路径 mkdir -p ~/.config/gcloud echo "${{ secrets.GOOGLE_APPLICATION_CREDENTIALS }}" > ~/.config/gcloud/application_default_credentials.json # 设置环境变量告知SDK凭证位置(可选,部分场景需要) echo "GOOGLE_APPLICATION_CREDENTIALS=~/.config/gcloud/application_default_credentials.json" >> $GITHUB_ENV - name: Run pytest run: pytest tests/ -v # 替换为你的测试目录 # Dockerfile Lint作业 hadolint: runs-on: ubuntu-latest steps: - name: Checkout code uses: actions/checkout@v4 - name: Run hadolint uses: hadolint/hadolint-action@v3.1.0 with: dockerfile: Dockerfile # 替换为你的Dockerfile路径 # Docker镜像构建推送作业(依赖前三个作业全部成功) docker-build-push: needs: [ pylint, pytest, hadolint ] runs-on: ubuntu-latest steps: - name: Checkout code uses: actions/checkout@v4 - name: Login to Docker Hub uses: docker/login-action@v3 with: username: ${{ secrets.DOCKER_HUB_USERNAME }} password: ${{ secrets.DOCKER_HUB_TOKEN }} - name: Set up Docker Buildx uses: docker/setup-buildx-action@v3 - name: Build and push uses: docker/build-push-action@v5 with: context: . push: true tags: ${{ secrets.DOCKER_HUB_USERNAME }}/your-image-name:dev # 替换为你的镜像标签
关键修复点说明
- 多作业隔离性处理:每个作业都是独立的运行环境,所以
pytest作业必须单独拉取代码、配置Python环境、引入所需密钥,不能依赖其他作业的状态。 - Google凭证注入:
- 确保仓库已添加名为
GOOGLE_APPLICATION_CREDENTIALS的密钥,值为你的Google服务账号JSON内容。 - 在
pytest作业中,将密钥内容写入Google SDK默认读取的文件路径~/.config/gcloud/application_default_credentials.json,同时通过环境变量指定路径,确保google-auth库能正确找到凭证。
- 确保仓库已添加名为
- 作业依赖配置:
docker-build-push作业通过needs字段指定依赖前三个作业,只有当pylint、pytest、hadolint全部成功时才会执行。
额外注意事项
- 替换配置中的Python版本、代码目录、测试目录、Dockerfile路径、镜像标签为你实际项目的信息。
- 确保
requirements.txt包含你的项目所有依赖,包括pytest和google-auth相关包。 - Docker Hub的密钥
DOCKER_HUB_USERNAME和DOCKER_HUB_TOKEN需要提前添加到仓库密钥中。
内容的提问来源于stack exchange,提问作者steveh
相关产品推荐
相关产品推荐

