Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I use an env file with GitHub Actions?

I have multiple environments (dev, qa, prod) and I'm using .env files to store secrets etc... Now I'm switching to GitHub Actions, and I want to use my .env files and declare them into the env section of the github actions yml.

But from what I've seen so far, it seems that I can not set a file path and I have to manually re-declare all variables.

How should I proceed as best practice?

like image 968
HRK44 Avatar asked Feb 11 '20 19:02

HRK44


People also ask

How do I pass an environment variable in GitHub actions?

To set a custom environment variable, you must define it in the workflow file. The scope of a custom environment variable is limited to the element in which it is defined. You can define environment variables that are scoped for: The entire workflow, by using env at the top level of the workflow file.

How do I add an environment variable to GitHub?

(After the setting, you can use environment variables like this in your project.) To add a secret to your repository, go to your repository's Setting > Secrets , click on Add a new secret .

Should I push .env to GitHub?

@xtremer360 You should keep the . env. example in your repository, and never include your . env file populated with sensitive information such as database credentials and API keys.


2 Answers

a quick solution here could be having a step to manually create the .env file before you need it.

- name: Create env file         run: |           touch .env           echo API_ENDPOINT="https://xxx.execute-api.us-west-2.amazonaws.com" >> .env           echo API_KEY=${{ secrets.API_KEY }} >> .env           cat .env  
like image 154
sugarcane Avatar answered Oct 23 '22 13:10

sugarcane


The easiest way to do this is to create the .env file as a github secret and then create the .env file in your action.
So step 1 is to create the .env files as a secret in github as a base64 encoded string:
openssl base64 -A -in qa.env -out qa.txt
or
cat qa.env | base64 -w 0 > qa.txt
Then in you action, you can do something like

- name: Do Something with env files   env:     QA_ENV_FILE: ${{ secrets.QA_ENV_FILE }}     PROD_ENV_FILE: ${{ secrets.PROD_ENV_FILE }}   run: |     [ "$YOUR_ENVIRONMENT" = qa ] && echo $QA_ENV_FILE | base64 --decode > .env     [ "$YOUR_ENVIRONMENT" = prod ] && echo $PROD_ENV_FILE | base64 --decode > .env 

There are a number of ways for determining $YOUR_ENVIRONMENT but usually this can be extracted from the GITHUB_REF object. You applications should be able to read from the .env files as needed.

like image 42
Brian Buccellato Avatar answered Oct 23 '22 12:10

Brian Buccellato