Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Get AWS CLI IAM credentials from LastPass CLI. Blog post: https://paulgalow.com/securing-aws-credentials-macos-lastpass
#!/bin/bash
# Get AWS CLI IAM credentials from LastPass CLI
# Blog post: https://paulgalow.com/securing-aws-credentials-macos-lastpass
# ##############################################################################
# Please adjust those properties
readonly lastPassEntry="REPLACE-ME" # Name of LastPass entry that stores your IAM credentials
readonly lpass="/usr/local/bin/lpass" # Path to LastPass CLI
# ##############################################################################
# Set up logging
info() { printf "[INFO] %s" "$*" 1> >(sed $'s,.*,\e[32m&\e[m,'); }
warning() { printf "[WARNING] %s" "$*" 1> >(sed $'s,.*,\e[33m&\e[m,'); }
error() { printf "[ERROR] %s" "$*" 1> >(sed $'s,.*,\e[35m&\e[m,'); exit 1; }
# ##############################################################################
# Set unofficial Bash strict mode
# Source: https://dev.to/thiht/shell-scripts-matter
set -euo pipefail
IFS=$'\n\t'
# ##############################################################################
# Check if operating system is macOS
checkOS() {
if [[ ! "$(uname)" = "Darwin" ]]; then return 1; fi
}
# Make sure this script is not being run as root
checkRoot() {
if [ "$EUID" -eq 0 ]; then return 1; fi
}
# Check if program is installed
checkInstalled() {
command -v "$1" > /dev/null
}
# Load credentials from LastPass CLI and deliver them as a JSON response
prepareCredentials() {
local -r accessKeyId=$($lpass show --username "$lastPassEntry")
local -r secretAccessKey=$($lpass show --password "$lastPassEntry")
# Check if both variables are not empty
if [[ -z "$accessKeyId" ]] || [[ -z "$secretAccessKey" ]]; then return 1; fi
# Create JSON object that AWS CLI expects
jq -n \
--arg accessKeyId "$accessKeyId" \
--arg secretAccessKey "$secretAccessKey" \
'.Version = 1
| .AccessKeyId = $accessKeyId
| .SecretAccessKey = $secretAccessKey'
}
# Run functions
checkOS || error "It seems you are not running macOS. Exiting..."
checkRoot || error "Please don't run this script with elevated privileges"
checkInstalled aws || error \
"AWS CLI not found. Please install, e.g. via Homebrew: 'brew install aws'"
checkInstalled lpass || error \
"lpass not found. Please install, e.g. via Homebrew: 'brew install lastpass-cli'"
checkInstalled jq || error \
"jq not found. Please install, e.g. via Homebrew: 'brew install jq'"
prepareCredentials || error \
"Could not get credentials from LastPass. Are you logged in? Try 'lpass login user@example.com'"
exit 0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.