Skip to content

Instantly share code, notes, and snippets.

@bonkydog
Last active August 29, 2015 14:08
Show Gist options
  • Select an option

  • Save bonkydog/4bdbce780cb12b2b0349 to your computer and use it in GitHub Desktop.

Select an option

Save bonkydog/4bdbce780cb12b2b0349 to your computer and use it in GitHub Desktop.
User data bash script to tag newly launched EC2 instance with its ssh host key fingerprint.
if curl -s http://169.254.169.254; then # looks like we're running on Amazon.
# Install Java
apt-get install -y openjdk-7-jre-headless
# Install EC2 command-line tools
wget https://s3.amazonaws.com/ec2-downloads/ec2-api-tools.zip
unzip ec2-api-tools.zip -d /usr/local/ec2
# Set up EC2 environment variables
export JAVA_HOME=/usr/lib/jvm/java-7-openjdk-amd64/jre
export EC2_HOME=$(ls -d /usr/local/ec2/* | head -1)
export PATH=$PATH:$EC2_HOME/bin
# Note that we don't set keys, because we are using IAM.
# Determine this machine's instance id.
instance_id=$(ec2metadata --instance-id)
# Determine this machine's RSA host key fingerprint.
fingerprint=$(ssh-keygen -l -f ssh-keygen -l -f /etc/ssh/ssh_host_rsa_key | awk '{print $2}')
# Tag the instance with the fingerprint so we can verify it when we ssh in for the first time.
ec2tag $instance_id --tag ssh-fingerprint=$fingerprint
fi
@bonkydog
Copy link
Author

Launch your instance with an IAM role that allows it to create tags:

{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Action": [
        "ec2:CreateTags"
      ],
      "Resource": [
        "*"
      ]
    }
  ]
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment