Skip to content

Instantly share code, notes, and snippets.

@sysboss
Created August 21, 2017 10:24
Show Gist options
  • Save sysboss/e2a119a391da8f9f3e660289aefd8ab7 to your computer and use it in GitHub Desktop.
Save sysboss/e2a119a391da8f9f3e660289aefd8ab7 to your computer and use it in GitHub Desktop.
Get all EC2 tags and set them as Bash variables
#!/bin/bash
#
# EC2 tags to variables
# Copyright (c) Alexey Baikov <sysboss[at]mail.ru>
#
# Description:
# Gets all EC2 tags and converts them to Bash variables
# Based on 'jq' (https://stedolan.github.io/jq/)
INSTANCE_REGION="$(curl -s http://169.254.169.254/latest/dynamic/instance-identity/document | grep region | tr -d ' ' | cut -f2 -d: | tr -d '"' | tr -d ',')"
INSTANCE_ID="$(curl -s http://169.254.169.254/latest/meta-data/instance-id)"
TAGS=$(aws ec2 describe-tags \
--filters "Name=resource-id,Values=${INSTANCE_ID}" \
--region ${INSTANCE_REGION})
COUNT=$(expr $(echo "${TAGS}" | jq '.Tags | length') - 1)
function getTagKey() {
echo "${TAGS}" | jq ".Tags[$1][\"Key\"]" | tr -d '"' | sed 's/:/_/g'
}
function getTagValue() {
echo "${TAGS}" | jq ".Tags[$1][\"Value\"]" | tr -d '"' | sed 's/:/_/g'
}
# run on each tag and
# declare it as environment variables
for i in $(seq 0 ${COUNT}); do
# set Key=Value
declare "$(getTagKey $i)=$(getTagValue $i)"
done
# Usage example:
# echo ${Name}
# echo ${aws_autoscaling_groupName}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment