Skip to content

Instantly share code, notes, and snippets.

@Kuzyashin
Last active August 3, 2020 10:04
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 Kuzyashin/49ca869ffa50df344351333c5a38a435 to your computer and use it in GitHub Desktop.
Save Kuzyashin/49ca869ffa50df344351333c5a38a435 to your computer and use it in GitHub Desktop.
user-data.sh
#!/usr/bin/env bash
#
# Get the value of a tag for a running EC2 instance.
#
# This can be useful within bootstrapping scripts ("user-data").
#
# Note the EC3 instance needs to have an IAM role that lets it read tags. The policy
# JSON for this looks like:
#
# {
# "Version": "2012-10-17",
# "Statement": [
# {
# "Effect": "Allow",
# "Action": "ec2:DescribeTags",
# "Resource": "*"
# }
# ]
# }
# Define the tag you want to get the value for
KEY=Name
# Install AWS CLI (you could just do 'apt-get install awscli' although you'll
# get an older version).
AWSCLI=$(which aws)
if [ -z "$AWSCLI" ]
then
apt-get update
sudo apt-get install -y unzip
curl "https://awscli.amazonaws.com/awscli-exe-linux-x86_64.zip" -o "awscliv2.zip"
unzip awscliv2.zip
sudo ./aws/install
sudo rm -rf ./aws/
sudo rm -rf awscliv2.zip
fi
# Grab instance ID and region as the 'describe-tags' action below requires them. Getting the region
# is a pain (see http://stackoverflow.com/questions/4249488/find-region-from-within-ec2-instance)
INSTANCE_ID=$(ec2metadata --instance-id)
REGION=$(curl -s http://169.254.169.254/latest/dynamic/instance-identity/document | grep region | awk -F\" '{print $4}')
# Grab tag value
TAG_VALUE=$(aws ec2 describe-tags --filters "Name=resource-id,Values=$INSTANCE_ID" "Name=key,Values=$KEY" --region=$REGION --output=text | cut -f5)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment