Skip to content

Instantly share code, notes, and snippets.

@bakatz
Last active August 8, 2024 02:26
Show Gist options
  • Save bakatz/6276daafbaf16084ca9919380e03424a to your computer and use it in GitHub Desktop.
Save bakatz/6276daafbaf16084ca9919380e03424a to your computer and use it in GitHub Desktop.
Import your .env files to GitHub Actions and generate a Kamal .env.erb referencing all of them
#!/bin/bash
# Check if .env file is provided as argument
if [ "$#" -ne 1 ]; then
echo "Usage: $0 <path-to-.env-file>"
exit 1
fi
ENV_FILE=$1
# Ensure gh is authenticated
gh auth status
if [ $? -ne 0 ]; then
echo "You must authenticate with the GitHub CLI first using 'gh auth login'"
exit 1
fi
# Initialize the .env.erb file for Kamal and all example files
ENV_ERB_FILE=".env.erb"
ENV_GH_EXAMPLE_FILE=".env.gh-actions.example"
ENV_GH_EXAMPLE2_FILE=".env.gh-actions.example2"
rm $ENV_ERB_FILE > /dev/null 2>&1
rm $ENV_GH_EXAMPLE_FILE > /dev/null 2>&1
rm $ENV_GH_EXAMPLE2_FILE > /dev/null 2>&1
# Read the .env file and set secrets
while IFS= read -r line
do
if [[ ! -z "$line" && "$line" != \#* ]]; then
KEY=$(echo $line | cut -d '=' -f 1)
VALUE=$(echo $line | cut -d '=' -f 2-)
# Remove leading and trailing quotes
VALUE=$(echo $VALUE | sed -e 's/^"//' -e 's/"$//')
VALUE=$(echo $VALUE | sed -e "s/^'//" -e "s/'$//")
gh secret set $KEY -b "$VALUE"
if [ $? -eq 0 ]; then
echo "$KEY=<%= ENV[\"$KEY\"] %>" >> $ENV_ERB_FILE
echo "$KEY: {{ secrets.$KEY }}" >> $ENV_GH_EXAMPLE_FILE
echo "- $KEY" >> $ENV_GH_EXAMPLE2_FILE
echo "✓ Wrote $KEY to $ENV_ERB_FILE and $ENV_GH_EXAMPLE_FILE, $ENV_GH_EXAMPLE2_FILE"
else
echo "❌ Failed to set secret $KEY"
fi
fi
done < "$ENV_FILE"
printf "\n🎉 Process done: set secret values in github, generated .env.erb for Kamal, and generated copy-pasta example yml to easily reference secrets in gh actions\n"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment