秘密在 GitHub Actions 工作流程中不可用

问题描述 投票:0回答:1

我在存储库设置下添加了秘密变量。这是我的目标:

  1. 从秘密中读取变量
  2. 注入环境以便应用程序可以读取它。

问题:

Secrets 在 mysql 初始化中工作得很好,但 Nodejs 代码抱怨并抛出错误,因为环境变量不存在。

# .github/workflows/nodejs.yml

name: Node.js CI

on:
  push:
    branches: [ "main" ]
  pull_request:
    branches: [ "main" ]

jobs:
  build:

    runs-on: ubuntu-latest

    strategy:
      matrix:
        node-version: [14.x, 16.x, 18.x]

    services:
      mysql:
        image: mysql:5.7
        env:
          # user: root, password: root (default)
          MYSQL_DATABASE: ${{ secrets.employeeadmin }}
          MYSQL_ROOT_PASSWORD: ${{ secrets.MYSQL_ROOT_PASSWORD }}
        ports:
          - 3306:3306
        options: --health-cmd="mysqladmin ping" --health-interval=10s --health-timeout=5s --health-retries=3

    steps:
    - uses: actions/checkout@v3
    - name: MySQL Initialization Script
      run: |
        mysql -h127.0.0.1 -u${{ secrets.MYSQL_USER }} -p${{ secrets.MYSQL_ROOT_PASSWORD }} -e "CREATE DATABASE IF NOT EXISTS ${{ secrets.MYSQL_DATABASE }};"
        mysql -h127.0.0.1 -u${{ secrets.MYSQL_USER }} -p${{ secrets.MYSQL_ROOT_PASSWORD }} ${{ secrets.MYSQL_DATABASE }} < assets/schema.sql
    - name: Use Node.js ${{ matrix.node-version }}
      uses: actions/setup-node@v3
      with:
        node-version: ${{ matrix.node-version }}
        cache: 'npm'
    - name: Start application
      run: sudo npm start
      env: # issue these variables are not available to nodejs app
        DATABASE_HOST: ${{secrets.DATABASE_HOST}}
        DATABASE_PORT: ${{secrets.DATABASE_PORT}}
        MYSQL_DATABASE: ${{secrets.MYSQL_DATABASE}}
        MYSQL_USER: ${{secrets.MYSQL_USER}}
        MYSQL_PASSWORD: ${{secrets.MYSQL_PASSWORD}}
        MYSQL_ROOT_PASSWORD: ${{secrets.MYSQL_ROOT_PASSWORD}}
    - name: Run tests
      run: npm test

截图

nodejs代码

let env = {
    "DATABASE_HOST": process.env.DATABASE_HOST,
    "DATABASE_PORT": process.env.DATABASE_PORT,
    "MYSQL_DATABASE": process.env.MYSQL_DATABASE,
    "MYSQL_USER": process.env.MYSQL_USER,
    "MYSQL_PASSWORD": process.env.MYSQL_PASSWORD
};

for (let key in env) {
    if(env[key] == null) throw new Error("Please set the " + key + " in env variables and try again.")
}

github-actions
1个回答
0
投票

事实证明这些变量仅适用于运行步骤

当您定义 env 块时,它会为其设置环境变量 具体运行步骤。不幸的是,它并没有直接影响 npm start 命令中的环境。相反,您应该使用 env 块直接在运行命令中。

© www.soinside.com 2019 - 2024. All rights reserved.