Why env in GitHub Actions?
Use environment variables for values you reuse across steps:
- API keys and DB URLs (via secrets)
- Server paths and ports
- App configuration (
NODE_ENV, feature flags)
1. Workflow-level env
env:
NODE_ENV: production
PORT: 3000
jobs:
build:
runs-on: ubuntu-latest
steps:
- run: echo $NODE_ENV2. Job-level env
jobs:
build:
runs-on: ubuntu-latest
env:
APP_NAME: my-app
steps:
- run: echo $APP_NAME3. Step-level env
steps:
- name: Run script
env:
API_URL: https://api.example.com
run: echo $API_URL4. Secrets (production)
Do not hardcode passwords, tokens, or private keys in YAML.
- Repo → Settings → Secrets and variables → Actions
- Add secrets such as
DB_URL,JWT_SECRET,EC2_IP - Reference them in the workflow:
env:
DB_URL: ${{ secrets.DB_URL }}5. Deploy-style example
jobs:
deploy:
runs-on: self-hosted
env:
APP_DIR: /home/ubuntu/app
steps:
- name: Pull Code
run: cd $APP_DIR && git pull
- name: Install
run: cd $APP_DIR && npm i
- name: Restart
run: pm2 restart appBest Practices
| Do | Don't |
|---|---|
| Use env for non-sensitive config | Commit secrets into the workflow file |
| Use GitHub Secrets for credentials | Print secrets in logs |
| Prefer one place to change paths / ports | Scatter hard-coded paths in every step |
env = reusable configuration; secrets = sensitive values injected at runtime.