Skip to content

Instantly share code, notes, and snippets.

@24HOURSMEDIA
Last active November 4, 2018 09:46
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save 24HOURSMEDIA/dd99eadd130058025a2c89816f69d0b1 to your computer and use it in GitHub Desktop.
Save 24HOURSMEDIA/dd99eadd130058025a2c89816f69d0b1 to your computer and use it in GitHub Desktop.
aws ec2 get instance and ami tags and write them to a file. here is the file and the policy for the AWS role needed om the instances
{
"Statement": [
{
"Effect": "Allow",
"Action": [
"ec2:DescribeInstances",
"ec2:DescribeTags"
],
"Resource": "*"
}
]
}
#!/bin/bash
# get_ec2tags
# this command outputs ec2 instance tags as an ini format variable set, and exports them as environment variables.
# the tag names are prefixed and uppified.
# Example output:
#INSTANCE_NAME=jbl-instance-tpl
#INSTANCE_ROLE=worker
#INSTANCE_AWS_AUTOSCALING_GROUPNAME=jbl-stack
# you can run this at boot time or with crons, and store the output in a file
# that can be sourced.
# i.e.
# ./get_ec2tags > environment
# you can then do:
# source environment
# adapted by 24hoursmedia from https://dev-ops-notes.com/aws/how-to-put-aws-ec2-tags-to-environment-variables/
REGION=`curl -s http://169.254.169.254/latest/dynamic/instance-identity/document|grep region|awk -F\" '{print $4}'`
uppify () {
echo $(echo $1 | iconv -t ascii//TRANSLIT | sed -r s/[^a-zA-Z0-9]+/_/g | sed -r s/^-+\|-+$//g | tr a-z A-Z)
}
get_instance_tags () {
instance_id=$(/usr/bin/curl --silent http://169.254.169.254/latest/meta-data/instance-id)
echo $(/usr/bin/aws ec2 describe-tags --filters "Name=resource-id,Values=$instance_id" --region=${REGION})
}
get_ami_tags () {
ami_id=$(/usr/bin/curl --silent http://169.254.169.254/latest/meta-data/ami-id)
echo $(/usr/bin/aws ec2 describe-tags --filters "Name=resource-id,Values=$ami_id" --region=${REGION})
}
tags_to_env () {
tags=$1
prefix=$2
for key in $(echo $tags | /usr/bin/jq -r ".[][].Key"); do
value=$(echo $tags | /usr/bin/jq -r ".[][] | select(.Key==\"$key\") | .Value")
key=$(echo $key | /usr/bin/tr '-' '_' | /usr/bin/tr '[:lower:]' '[:upper:]')
#export $key="$value"
uppified_key=$(uppify "$key")
export $prefix$uppified_key="$value"
echo $prefix$uppified_key="$value"
done
}
ami_tags=$(get_ami_tags)
instance_tags=$(get_instance_tags)
tags_to_env "$ami_tags" "AMI_"
tags_to_env "$instance_tags" "INSTANCE_"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment