Skip to content

Instantly share code, notes, and snippets.

@manics
Created March 20, 2023 13:27
Show Gist options
  • Save manics/cda4e63e9e3ab42a617100465bbbde85 to your computer and use it in GitHub Desktop.
Save manics/cda4e63e9e3ab42a617100465bbbde85 to your computer and use it in GitHub Desktop.
"aws ec2 get-password-data" for Ubuntu
#!/bin/sh
# Based on Windows EC2Launch Module/Scripts/Send-AdminCredentials.ps1 script
#
# Include this at the end of your EC2 userdata
# Once the console output is available you should be able to run
# aws ec2 get-password-data --instance-id=INSTANCE_ID --priv-launch-key SSH_PRIVATE_PEM_FILE
# to get the randomly generated password
#
# Note that SSH password authentication is disabled on the SSH server by default
set -eu
USERNAME=ubuntu
PASSWORD=`openssl rand -base64 18`
# Assume cloud-init will set authorized_keys to the SSH public key
PUBLIC_KEY="/home/$USERNAME/.ssh/authorized_keys"
# Just in case there are multiple
head -n1 "$PUBLIC_KEY" > ssh_public_key.pub
ssh-keygen -f ssh_public_key.pub -e -m PKCS8 > ssh_public_key.pem.pub
ENCRYPTED_PASSWORD=`echo -n "$PASSWORD" | openssl pkeyutl -encrypt -pubin -inkey ssh_public_key.pem.pub | base64`
# This is an important step to inform console about the password reset.
# The format MUST NOT be changed!
timestamp=`date -u "+%Y/%m/%d %H:%M:%SZ"`
# Output as a single block, to avoid interleaving with other console output
cat << EOF > /dev/console
$timestamp: Username: $USERNAME
$timestamp: Password: <Password>
$ENCRYPTED_PASSWORD
</Password>
EOF
# Only change the password if there were no errors
echo "$USERNAME:$PASSWORD" | chpasswd
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment