figtrap
2/18/2016 - 8:34 PM

ec2-get-tag function for retrieving tag values in Amazon EC2

ec2-get-tag function for retrieving tag values in Amazon EC2

get-tag() {
    # takes one arg, the tag key, which must be enclosed in double quotes
    # needs /usr/bin/aws, /usr/bin/jq, /usr/bin/curl
    AWS_DEFAULT_REGION=${AWS_DEFAULT_REGION-:us-east-1}
    local metadata_uri="http://169.254.169.254/latest/meta-data"
    local instance_id=$(/usr/bin/curl -s "${metadata_uri}"/instance-id)
    [ -z "${instance_id}" ] && { printf %s "could not get EC2 instance id" ; return 1 ; }
    local tag_value
    tag_value=$(/usr/bin/aws ec2 describe-tags --filters "Name=resource-id,Values=${instance_id}" \
        | /usr/bin/jq -r '.Tags[] | select(.Key == "'${1}'") | .Value')
    [ -z "${tag_value}" ] && { printf %s "null" ; return 1 ; }
    printf %s "${tag_value//\"/}"
    [ ! -z "$PS1" ] && printf "\n"
}