GitHub Actions用服务密钥认证Google Cloud报错:JSON解析异常
问题:GitHub Action中Google Cloud认证JSON解析失败
运行GitHub Action时触发报错:
Error: google-github-actions/auth failed with: retry function failed after 1 attempt: failed to parse service account key JSON credentials: unexpected token in JSON at position 0
服务账号密钥JSON格式(已脱敏):
{ "type": "service_account", "project_id": "", "private_key_id": "", "private_key": "-----BEGIN PRIVATE KEY-----\n-----END PRIVATE KEY-----\n", "client_email": "", "client_id": "", "auth_uri": "https://accounts.google.com/o/oauth2/auth", "token_uri": "https://oauth2.googleapis.com/token", "auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs", "client_x509_cert_url": "" }
Workflow配置片段:
- id: 'auth' name: 'Authenticate to Google Cloud' uses: 'google-github-actions/auth@v1' with: credentials_json: $GOOGLE_CREDENTIALS - id: 'upload-file' name: 'Upload report to Google Cloud' uses: 'google-github-actions/upload-cloud-storage@v0' with: path: $GITHUB_WORKSPACE/mochawesome-report destination: api-test-results parent: false glob: '*.html' - uses: 'google-github-actions/upload-cloud-storage@v0' if: always() env: SLACK_URL: ${{ secrets.SLACK_URL }} GOOGLE_CREDENTIALS: ${{ secrets.GOOGLE_CREDENTIALS }}
问题原因及解决方法
核心原因:认证步骤中引用GitHub Secret的方式错误。
credentials_json: $GOOGLE_CREDENTIALS没有使用GitHub Secrets的正确语法,导致实际传入的不是完整的服务账号密钥JSON内容,而是空值或无效字符串,JSON解析器在位置0就遇到意外字符,触发报错。解决方法:将认证步骤里的
$GOOGLE_CREDENTIALS替换为${{ secrets.GOOGLE_CREDENTIALS }},正确引用GitHub Secret:- id: 'auth' name: 'Authenticate to Google Cloud' uses: 'google-github-actions/auth@v1' with: credentials_json: ${{ secrets.GOOGLE_CREDENTIALS }}额外优化:后面的
upload-cloud-storage步骤不需要再设置GOOGLE_CREDENTIALS环境变量,因为auth步骤已经完成认证并设置了后续步骤可用的凭据,多余的设置可以删除,避免不必要的混淆。
内容的提问来源于stack exchange,提问作者George
相关产品推荐
相关产品推荐

