githubgithub-actionsgithub-secret

GitHub Action for adding all variables and secrets to .env.local


I was searching a lot how to add all the GitHub variables and secrets in a file without concerning about them.

Now I am using this manual solution. Which forces me to always change here according to the new added/removed variables/secrets:

- name: ▶️ 4. Create .env.local file
  run: |
    touch .env.local
    echo DB_CONN_DEFAULT_NAME="${{ secrets.DB_CONN_DEFAULT_NAME }}" >> .env.local
    echo DB_CONN_DEFAULT_USERNAME="${{ secrets.DB_CONN_DEFAULT_USERNAME }}" >> .env.local
    echo DB_CONN_DEFAULT_PASSWORD="${{ secrets.DB_CONN_DEFAULT_PASSWORD }}" >> .env.local
    echo FILESTORAGE_MAIN__LOCATION_UPLOADS="${{ secrets.FILESTORAGE_MAIN__LOCATION_UPLOADS }}" >> .env.local
    echo WEB_URL="${{ vars.WEB_URL }}" >> .env.local

My Problem

I couldn't find, as far as I searched for it, a GitHub action which iterates through variables and secrets and put all of them in a file.

Or it could be a yaml syntax for looping through them. Do you have any idea?

Question: what would be the solution to not write them manually in my .env.local file?


Update

I tried what @Azeem adviced me in his comments.

Here is the workflow output and the error:

Run touch .env.local
  touch .env.local
  
  echo "# GitHub variables"
  echo "{
    "APP__BOS_WEBSITE__WEB_URL": "---",
    "APP__LEARNING_SPACE__WEB_URL": "---",
    "APP__WEBDEV_SPACE__WEB_URL": "---",
    "APP__WEBWORK_SPACE__WEB_URL": "---",
    "WEB_URL": "---"
  }" | jq -r 'keys[] as $k | "\($k)=\(.[$k])"' >> .env.local
  
  echo "# GitHub secrets"
  echo "{
    "FTP_USERNAME": "***",
    "github_token": "***",
    "DB_CONN_MAIN_USERNAME": "***",
    "FILESTORAGE_MAIN__LOCATION_UPLOADS": "***",
    "DB_CONN_MAIN_PASSWORD": "***",
    "FTP_PASSWORD": "***",
    "FILESTORAGE_WEBDEV__LOCATION_UPLOADS": "***",
    "FILESTORAGE_WEBSITE__LOCATION_UPLOADS": "***",
    "DB_CONN_MAIN_NAME": "***",
    "FTP_SERVER_DIR": "***"
  }" | jq -r 'keys[] as $s | "\($s)=\(.[$s])"' >> .env.local

  shell: /usr/bin/bash -e {0}
  env:
    COMPOSER_PROCESS_TIMEOUT: 0
    COMPOSER_NO_INTERACTION: 1
    COMPOSER_NO_AUDIT: 1
    CACHE_RESTORE_KEY: Linux-php-7.4.33-composer-locked-

# GitHub variables
parse error: Invalid numeric literal at line 2, column 28
Error: Process completed with exit code 4.

Solution

  • You can use toJSON function and jq to dump secrets context in a .env file:

    echo '${{ toJSON(secrets) }}' | jq -r 'keys[] as $k | "\($k)=\(.[$k])"' >> .env.local
    

    Here's another similar thread involving vars context:

    How to inject all Github environment-specific variables from vars to env context?