Created
December 5, 2023 12:37
-
-
Save xbb/fb0e20812fb305a55c57cb03c4d8d475 to your computer and use it in GitHub Desktop.
Login to Teleport with 1Password CLI
This file contains hidden or 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
#!/usr/bin/env bash | |
set -e | |
main() { | |
case $1 in | |
help) show_help ;; | |
*) load_profile "$1" ;; | |
esac | |
set -u | |
run | |
} | |
show_help() { | |
echo "Usage: $(basename "${BASH_SOURCE[0]}")" '<profile_name>' | |
show_help_profile | |
} | |
show_help_profile() { | |
cat <<'EOF' | |
Profiles are bash scripts sourced from: | |
~/.config/op-tsh-login/<profile_name> | |
Example configuration: | |
# 1password account login url | |
export OPTP_ACCOUNT_URL='example.1password.com' | |
# 1password item field path op://<vault>/<item>/<field> | |
export OPTP_USER='op://Private/Teleport/username' | |
export OPTP_PASS='op://Private/Teleport/password' | |
# Teleport proxy URL | |
export OPTP_PROXY='teleport.example.com' | |
EOF | |
} | |
load_profile() { | |
if test -z "$1"; then | |
>&2 show_help | |
exit 1 | |
fi | |
if [[ "$1" =~ [^a-zA-Z0-9] ]]; then | |
>&2 echo "Invalid profile name: $1" | |
exit 1 | |
fi | |
local config_dir="$HOME/.config/op-tsh-login" | |
local profile="$config_dir/$1" | |
if ! test -d "$config_dir"; then | |
mkdir -p "$config_dir" | |
fi | |
if ! test -f "$profile"; then | |
>&2 echo "Error: $profile does not exist" | |
>&2 show_help_profile | |
exit 1 | |
fi | |
source "$profile" | |
} | |
tsh_status() { | |
tsh status 2>&1 | |
} | |
check_status() { | |
local status= | |
status="$(tsh_status)" || return 0 | |
>&2 printf "Already logged in:\n\n%s\n" "$status" | |
>&2 printf "\nTo logout use:\n\n tsh logout\n" | |
return 2 | |
} | |
run() { | |
check_status | |
op run -- expect -c "$(cat <<'EOF' | |
set USERNAME $env(TP_USER) | |
spawn tsh login --proxy "$env(TP_PROXY)" --user "$env(TP_USER)" | |
expect -re "Enter password for Teleport user $USERNAME*" { | |
send -- "$env(TP_PASS)\n" | |
interact | |
} | |
EOF | |
)" | |
} | |
main "$@" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I updated this for
fish
with a few enhancements like colors, formatting, otp, a single env variable.There are some limitations like how
op get item
only will look at domain name (not sub domains). I haven't added handling for when multiple items match, so that may be a future enhancement if I end up with more entries on the same domain name.This also doesn't handle cases where a user isn't using a otp.