DEV Community

Cover image for How to set .env variables to Heroku dynamically with a .sh script
Lucas Vieira
Lucas Vieira

Posted on • Updated on

How to set .env variables to Heroku dynamically with a .sh script

One of the things I really missed when I started using .env files to securelly store important variables, instead of just putting it in the source code, was the abillity to push them to my remote effectivelly.

Code to send .env variables to heroku

After some reasearch, I didn’t found anything related so I decide to code it myself. And here is the result:

#!/bin/bash
# USAGE: bash addEnvToHeroku.sh <filepath>

# SET VARIABLES ________________________________________________________________
input=$1
output=$1.sh

# DEFINE FUNCTION TO DELETE FILE _______________________________________________
function deleteIfExist {
   if test -f "$1"; then
      echo "$1 exists."
      unlink "$1"
   fi
}

# SHOW SCRIPT TITLE ____________________________________________________________
echo -e "Setting heroku variables for the file $input: \n"

# DELETE THE SH FILE IF IT EXISTS ______________________________________________
deleteIfExist "$output"

# READ THE CONTENT AND SAVE IN A SH FILE _______________________________________
while read -r line; do
   echo "heroku config:set $line" >> "$output"
done < "$input"

# EXECUTE THE SH FILE __________________________________________________________
bash "$output"

# DELETE THE SH FILE IF IT EXISTS ______________________________________________
deleteIfExist "$output"
Enter fullscreen mode Exit fullscreen mode

Configuration if you’re using Windows

As you can see, it is a .sh file, but you can run it in Windows as well, you just need to specify the git bash location in your .bashrc file, which is located in C:\user\[your user name]\.bashrc, as it is show bellow:

alias bash='"C:\\Program Files\\Git\\bin\\bash.exe'
Enter fullscreen mode Exit fullscreen mode

How to use

Now let’s see a simple example on how to use the script.

# Create a project folder
mkdir MySimplepProject

# Go to the project path
cd MySimpleProject

# Initialize git
git init

# Select your heroku app
heroku git:remote -a mySimpleProjectInHeroku

# supposing you have a ".env" and "addEnvToHeroku.sh" in the project root

# Send the .env variables to heroku
bash addEnvToHeroku.sh ".env"
Enter fullscreen mode Exit fullscreen mode

And if you go to heroku you should see all your .env variables:

Image description

Now you can change and update these variables quicker and easier! 🀘

RELATED

πŸ‘‰ you can also find the above mentionated code in this repository
πŸ‘‰ See also all my projects
πŸ‘‰ See also all my tutorials

Top comments (0)