Created
October 25, 2023 10:34
-
-
Save mrantivirus/2b834a58f86431babcf022b0cfbaa702 to your computer and use it in GitHub Desktop.
Bash script to export a 1Password item to a dotenv file
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
# 1password_to_dotenv.sh | |
# Script to fetch fields from a 1Password item and save them as dotenv entries with secret references. | |
# Ensure `op` is logged in | |
if ! op user get --me >/dev/null 2>&1; then | |
echo "You need to sign in to op (1Password CLI) first." | |
exit 1 | |
fi | |
# Default path for the dotenv file | |
DOTENV_PATH="./exported.env" | |
# Parse arguments | |
while [[ "$#" -gt 0 ]]; do | |
case $1 in | |
-h|--help) | |
echo "Usage: $0 ITEM_NAME [-v VAULT] [-o OUTPUT_PATH]" | |
echo "" | |
echo "ITEM_NAME: Name of the 1Password item" | |
echo "-v VAULT: Name of the 1Password vault (optional)" | |
echo "-o OUTPUT_PATH: Path to save the dotenv file" | |
exit 0 | |
;; | |
-v) VAULT="$2"; shift ;; | |
-o) DOTENV_PATH="$2"; shift ;; | |
*) ITEM_NAME="$1" ;; | |
esac | |
shift | |
done | |
# Validate the required arguments | |
if [[ -z "$ITEM_NAME" ]]; then | |
echo "Error: ITEM_NAME is required." | |
echo "Run '$0 --help' to see usage information." | |
exit 1 | |
fi | |
# Fetch item details | |
if [[ ! -z "$VAULT" ]]; then | |
ITEM_DETAILS=$(op item get "$ITEM_NAME" --vault "$VAULT" --format=json) | |
else | |
ITEM_DETAILS=$(op item get "$ITEM_NAME" --format=json) | |
fi | |
# Generic fields to filter out | |
GENERIC_FIELDS="notesPlain" | |
# Extract fields, filter out empty labels and generic fields, and write to dotenv | |
echo "$ITEM_DETAILS" | jq --arg generic "$GENERIC_FIELDS" -r '.fields[] | select((.label != null) and (.label != "" and .label != $generic)) | "\(.label)=\(.reference)"' > "$DOTENV_PATH" | |
echo "Exported 1Password fields to $DOTENV_PATH" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
1Password to .env Exporter
This script,
1password_to_dotenv.sh
, fetches fields from a specified 1Password item and saves them as dotenv entries with secret references.Prerequisites
op
(1Password CLI) installed and configured.jq
is installed for JSON parsing.Usage
Parameters:
./exported.env
in the current directory.Examples:
To export an item named "DatabaseCreds" from the default vault:
To export an item named "DatabaseCreds" from a vault named "WorkVault":
To export an item named "DatabaseCreds" from the default vault and save it to
~/myapp/.env
:./1password_to_dotenv.sh DatabaseCreds -o ~/myapp/.env
Notes
op
). The script will remind you to sign in if you haven't already..env
file will contain references to the 1Password secrets, not the actual secrets themselves.