GitHub Actions可复用工作流中仓库密钥传递失败问题
解决GitHub Actions可复用工作流中GCP服务账号密钥解析失败问题
问题背景
我有一个用于GCP身份认证的GitHub Actions仓库密钥,在密钥所在仓库的工作流中使用完全正常:
name: Auth to Google Cloud on: push: branches: [ master ] jobs: build: env: SERVICE_ACCOUNT: 'some-account.iam.gserviceaccount.com' runs-on: ubuntu-latest steps: - uses: actions/checkout@v3 - id: auth name: Authenticate to Google Cloud uses: google-github-actions/auth@v1 with: service_account: $SERVICE_ACCOUNT credentials_json: ${{ secrets.GCP_SA_KEY }}
但使用可复用工作流时,认证步骤失败,报错信息如下:
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
调用方工作流代码
name: Re-usable Demo on: push: branches: [ master ] workflow_dispatch: jobs: call-reusable-workflow: uses: my-organization/reusable-workflows/.github/workflows/reusable-workflow.yml@master with: service-account: 'some-account.iam.gserviceaccount.com' secrets: gcp-sa-key: ${{ secrets.GCP_SA_KEY }}
可复用工作流代码(位于另一个仓库)
name: Re-usable Workflow on: workflow_call: inputs: service-account: required: true type: string secrets: gcp-sa-key: required: true jobs: build: env: SERVICE_ACCOUNT: ${{ inputs.service-account }} GCP_SA_KEY: ${{ secrets.gcp-sa-key }} runs-on: ubuntu-latest steps: - uses: actions/checkout@v3 - id: auth name: Authenticate to Google Cloud uses: google-github-actions/auth@v1 with: service_account: $SERVICE_ACCOUNT credentials_json: $GCP_SA_KEY
注:服务账号已通过打印验证可正确传递,仅密钥无法正常工作,尝试过直接使用密钥不存入环境变量、将密钥作为输入传递均无效。
问题原因
GitHub Actions的机密(secrets)在传递到可复用工作流后,若存入环境变量会自动被转义,导致JSON格式的GCP服务账号密钥出现语法错误,无法被google-github-actions/auth动作正确解析。
解决方法
直接在auth步骤中引用可复用工作流的机密,跳过环境变量存储环节:
修改可复用工作流的build任务部分:
jobs: build: env: SERVICE_ACCOUNT: ${{ inputs.service-account }} runs-on: ubuntu-latest steps: - uses: actions/checkout@v3 - id: auth name: Authenticate to Google Cloud uses: google-github-actions/auth@v1 with: service_account: $SERVICE_ACCOUNT credentials_json: ${{ secrets.gcp-sa-key }}
可选调试步骤
若需确认机密内容是否正确传递,可添加临时打印步骤(生产环境务必删除):
- name: Debug secret content run: echo "${{ secrets.gcp-sa-key }}" | jq '.'
内容的提问来源于stack exchange,提问作者Stan Ostrovskii
相关产品推荐
相关产品推荐

