I normally load tags as environment variables on boot by running a UserData script. Depending on the instance, I change the --query
and --filter
parameters to the describe-instances
call but otherwise the script stays the same. NOTE: The example below excludes the tag Name
and tags containing :
- change this behaviour to suit your needs.
#!/bin/bash -v
apt-get update
apt-get -y install awscli
# add boot script which loads environment variables
cat > /etc/profile.d/export_instance_tags.sh << 'EndOfMessage'
# fetch instance info
INSTANCE_ID=$(curl -s http://169.254.169.254/latest/meta-data/instance-id)
INSTANCE_AZ=$(curl -s http://169.254.169.254/latest/meta-data/placement/availability-zone)
INSTANCE_REGION="`echo \"$INSTANCE_AZ\" | sed -e 's:\([0-9][0-9]*\)[a-z]*\$:\\1:'`"
# export instance tags
export_statement=$(aws ec2 describe-tags --region "$INSTANCE_REGION" --filters "Name=resource-id,Values=$INSTANCE_ID" --query 'Tags[?!contains(Key, `Name`) && !contains(Key, `:`)].[Key,Value]' --output text | sed -E 's/^([^\s\t]+)[\s\t]+([^\n]+)$/export \1="\2"/g')
eval $export_statement
# export instance info
export INSTANCE_ID
export INSTANCE_AZ
export INSTANCE_REGION
EndOfMessage
It runs describe-tags
to list all tags, reformats the output to a sequence of export statements with sed
then runs the result using eval