Skip to content

Instantly share code, notes, and snippets.

@rossigee
Created September 6, 2023 07:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rossigee/05048dae301864d180773f3d31208c24 to your computer and use it in GitHub Desktop.
Save rossigee/05048dae301864d180773f3d31208c24 to your computer and use it in GitHub Desktop.
Fetch Windows Administrator password from EC2 using Terragrunt/Terraform state
#!/usr/bin/env bash
#
# Run this in the Terraform folder for the instance to reconstruct the Administator password.
#
# Example usage:
#
# get-windows-administrator-password
#
INSTANCE_ID=$1
if [ $# -lt 1 ]; then
echo "Usage: aws-vault exec <aws_profile> -- $(basename $0) <instance-id>"
echo
echo "Example:"
echo " Run this in the Terraform folder for the instance..."
echo " $ aws-vault exec aws-production -- get-windows-administrator-password i-02e489efd1465b699"
exit 1
fi
if [ "$AWS_SESSION_TOKEN" = "" ]; then
echo "No AWS environment set. Maybe you forgot to use 'aws-vault'?"
exit 1
fi
# Fetch Terraform state
echo "Fetching Terraform state..."
terragrunt state pull >tfstate.tmp
if [ $? -ne 0 ]; then
echo "Unable to pull TF state."
exit 1
fi
# Clean up unwanted output pollution from Terragrunt
sed -i '1,2d; $d' tfstate.tmp
echo "Extracting private key..."
cat tfstate.tmp | jq -r '.resources[] | select(.name == "instance-pkey") | .instances[].attributes.private_key_pem' >tmp.keydata
if [ $? -ne 0 ]; then
echo "Unable to extract private key data."
exit 1
fi
echo "Using private key to retrieve instance password from Amazon..."
aws ec2 get-password-data --output=json --instance-id $INSTANCE_ID --priv-launch-key tmp.keydata
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment