Skip to content

Instantly share code, notes, and snippets.

@adrien2p
Last active March 1, 2022 09:41
Show Gist options
  • Save adrien2p/0d149db88c1aa7f22506a1c546388aa7 to your computer and use it in GitHub Desktop.
Save adrien2p/0d149db88c1aa7f22506a1c546388aa7 to your computer and use it in GitHub Desktop.
🔧 Add your env variables to your Heroku app smoothly 🚀
#!/usr/bin/env bash
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[0;33m'
BLUE='\033[0;34m'
NC='\033[0m'
usage="
A quick script to add env variables to your heroku application. Following options are required:
-h, [--help] | show this help text
-f=, [--file=] | env file path
Sample command: ./$(basename "$0") -f='.env'
"
# Reading input options
for i in "$@"; do
case $i in
-f=*|--file=*)
FILE="${i#*=}"
;;
-h*|--help*)
printf "$usage"
exit 0
;;
*)
# ignoring unknown option
;;
esac
done
# Check if -f option is present
if [ -z $FILE ]
then
echo -e "${YELLOW}--file${NC} ${RED}option missing${NC}. Use --help option to know the command\n"
exit 1
fi
echo -e "\n${BLUE}---> Looking for your envs${NC}\n"
ENVS=""
while IFS='=' read key value; do
# Check that the key is not empty and that it does not start with "#" to avoid comment
if [[ ! -z "$key" && ! $key =~ ^#.* ]]; then
echo -e "$key=$value"
ENVS="$ENVS $key=$value"
fi
done < "$FILE"
echo -e "\n${BLUE}---> Set all env to the following app ${NC}\n"
heroku apps:info
echo -e "\n${BLUE}---> Setting up the envs ${NC}\n"
heroku config:set $ENVS
@VxJasonxV
Copy link

VxJasonxV commented Feb 28, 2022

Related to previous revision
The new version includes the changes from the comment below

heroku config:set can take multiple vars set in a single command. Each config command invocation creates a new release of your app, if you run this and it sets 5 config vars it will create 5 builds. This is inefficient. All config vars being set / changed should be done in a single operation, a single heroku config:set command invocation.

Additionally, scripting a command line utility is brittle via an external process is brittle. If you're making an external helper utility, use Heroku's Platform API https://devcenter.heroku.com/articles/platform-api-reference#config-vars

There are a number of other pieces of low hanging fruit here, such as -s, apps are not servers. I recommend -a as that is the same flag used by the Heroku CLI. There is also detection magic the Heroku CLI employs, such as specification not only by app name (-a), but git remote name (-r), and also auto detection of the app name based off the git repository's heroku remote URL. None of which are preserved in this helper script.

@adrien2p
Copy link
Author

adrien2p commented Feb 28, 2022

@VxJasonxV Ill look into that and improve the script, thank you for your feedback, it is appreciated. 🚀

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment