Skip to content

Instantly share code, notes, and snippets.

@BSoDium
Last active March 5, 2025 18:41
Show Gist options
  • Save BSoDium/b323d5f3721049c1d9424b277daa002a to your computer and use it in GitHub Desktop.
Save BSoDium/b323d5f3721049c1d9424b277daa002a to your computer and use it in GitHub Desktop.
A script that creates a .env file containing all the secrets for the provided project name
#!/bin/bash
# Function to display help message
show_help() {
cat << EOF
Usage: ${0##*/} [-h] [PROJECT_NAME] [OUTPUT_PATH]
Retrieve secrets for a given project using 'bws' and write them to a .env file.
Arguments:
PROJECT_NAME Optional. The name of the project to retrieve secrets from. Defaults to the name of the current directory.
OUTPUT_PATH Optional. The directory where the .env file will be created. Defaults to the current directory.
Options:
-h, --help Display this help message and exit.
Examples:
~/projects/my-project> ${0##*/}
~/projects/my_renamed_project> ${0##*/} my-project
~/projects> ${0##*/} my-project ./my-project
EOF
}
# Check for help flag
if [[ "$1" == "-h" || "$1" == "--help" ]]; then
show_help
exit 0
fi
# Set project NAME
PROJECT_NAME="${1:-$(basename "$(pwd)")}"
# Retrieve project ID from `bws project list`
PROJECT_ID=$(bws project list --output json | jq -r ".[] | select(.name == \"$PROJECT_NAME\") | .id")
# Check if the command succeeded
if [[ $? -ne 0 ]]; then
echo "× Error: Failed to retrieve project ID. Ensure 'bws' is installed, the project name is correct. Is BWS_ACCESS_TOKEN properly set?"
exit 1
fi
# Check if project ID was found
if [[ -z "$PROJECT_ID" ]]; then
echo "× Error: Project '$PROJECT_NAME' not found. Ensure the project exists and you have access to it."
exit 1
fi
# Set output path
OUTPUT_PATH="${2:-.}"
ENV_FILE="$OUTPUT_PATH/.env"
# Ensure output path exists and is writable
if [[ ! -d "$OUTPUT_PATH" ]]; then
echo "× Error: Output path '$OUTPUT_PATH' does not exist."
exit 1
fi
if [[ ! -w "$OUTPUT_PATH" ]]; then
echo "× Error: No write permission for output path '$OUTPUT_PATH'."
exit 1
fi
# Retrieve secrets from BWS
echo "⇅ Fetching secrets for project: $PROJECT_ID"
SECRETS=$(bws secret list "$PROJECT_ID" --output env)
# Check if the command succeeded
if [[ $? -ne 0 ]]; then
echo "× Error: Failed to retrieve secrets. This should not happen, since the project ID was retrieved successfully."
exit 1
fi
# Write secrets to .env file
echo "↪ Writing secrets to $ENV_FILE..."
echo "# Auto-generated .env file" > "$ENV_FILE"
echo "$SECRETS" >> "$ENV_FILE"
echo "✔︎ .env file created successfully at $ENV_FILE."
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment