Skip to content

Instantly share code, notes, and snippets.

@ceelian
Created March 15, 2025 15:16
Show Gist options
  • Save ceelian/3b0751d642bf5b70a3d522b9e32dfb99 to your computer and use it in GitHub Desktop.
Save ceelian/3b0751d642bf5b70a3d522b9e32dfb99 to your computer and use it in GitHub Desktop.
A helper script for making it easy to locally set the 1Password service account token as environment variable for the op cli. This helps in keeping secrets scoped and in memory only without saving them to files.
#!/usr/bin/env bash
# Just a note: Don't use 'set -e' when meant to be sourced
# as it would exit the parent shell if there's an error
show_help() {
echo "Script for setting 1Password service account token in environment variable"
echo "Usage: source $(basename "$0") <op-reference|unset>"
echo " source $(basename "$0")"
echo "Example: source $(basename "$0") 'op://vault/item/field'"
echo " source $(basename "$0") unset"
echo " source $(basename "$0")"
}
ENV_VAR_NAME="OP_SERVICE_ACCOUNT_TOKEN"
SECRET_REF="$1"
# Show help if requested
if [ "$SECRET_REF" = "-h" ] || [ "$SECRET_REF" = "--help" ]; then
show_help
return 0 2>/dev/null || exit 0
fi
# Check if script is sourced, otherwise we can't export the variable
if [[ "${BASH_SOURCE[0]}" == "${0}" ]]; then
echo "ERROR: This script must be sourced, not executed."
exit 1
fi
## No Arguments where passed prompt user for token
if [ $# -lt 1 ]; then
echo -n "Enter the service account token: "
read -s SECRET
echo
export "$ENV_VAR_NAME"="$SECRET"
echo "$ENV_VAR_NAME has been set in your environment"
return 0 2>/dev/null || exit 0
fi
## Argument was passed check if it is unset
if [ "$SECRET_REF" = "unset" ]; then
unset $ENV_VAR_NAME
echo "$ENV_VAR_NAME has been unset from your environment"
return 0 2>/dev/null || exit 0
fi
## Argument must be a 1Password reference
# Check if op CLI is installed
if ! command -v op &> /dev/null; then
echo "Error: 1Password CLI (op) is not installed or not in PATH"
echo "Please install from https://1password.com/downloads/command-line/"
return 1 2>/dev/null || exit 1
fi
# Check if user is signed in to 1Password
if ! op account list &> /dev/null; then
echo "Error: Not signed in to 1Password. Please run 'op signin' first."
return 1 2>/dev/null || exit 1
fi
# Get the secret from 1Password
echo "Retrieving Service Account Token from '$SECRET_REF'"
if ! SECRET=$(op read "$SECRET_REF" 2>&1); then
echo "Error: Failed to retrieve token from 1Password: $SECRET"
return 1 2>/dev/null || exit 1
fi
# Export the secret to the environment
export "$ENV_VAR_NAME"="$SECRET"
echo "$ENV_VAR_NAME has been set in your environment"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment